【问题标题】:Transfer JSON to server in post request在 post 请求中将 JSON 传输到服务器
【发布时间】:2013-04-19 19:36:14
【问题描述】:

服务器采用两个参数:StringJSON。 提示,我正确地在 POST 请求中传输JSON 和字符串?

try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("my_url");
    List parameters = new ArrayList(2);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("par_1", "1");
    jsonObject.put("par_2", "2");
    jsonObject.put("par_3", "3");
    parameters.add(new BasicNameValuePair("action", "par_action"));
    parameters.add(new BasicNameValuePair("data", jsonObject.toString()));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    Log.v("Server Application", EntityUtils.toString(httpResponse.getEntity())+" "+jsonObject.toString());

} catch (UnsupportedEncodingException e) {
    Log.e("Server Application", "Error: " + e);
} catch (ClientProtocolException e) {
    Log.e("Server Application", "Error: " + e);
} catch (IOException e) {
    Log.e("Server Application", "Error: " + e);
} catch (JSONException e) {
    e.printStackTrace();
}

【问题讨论】:

  • 您是否遇到错误?你的问题到底是什么?
  • 没有错误。我的问题 - 这个实现正确传输 JSON 吗?

标签: android json post http-post


【解决方案1】:

我不确定您的问题是什么,但这是我发送 JSON 的方式(使用您的数据示例)。

Android/JSON 构建:

JSONObject jo = new JSONObject();
jo.put("action", "par_action");
jo.put("par_1", "1");
jo.put("par_2", "2");
jo.put("par_3", "3");

Android / 发送 JSON:

URL url = new URL("http://domaintoreceive.com/pagetoreceive.php");

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());

// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

// Set up the header types needed to properly transfer JSON
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");

// Execute POST
response = httpClient.execute(httpPost);

PHP/服务器端:

<?php
if (file_get_contents('php://input')) {
    // Get the JSON Array
    $json = file_get_contents('php://input');
    // Lets parse through the JSON Array and get our individual values
    // in the form of an array
    $parsedJSON = json_decode($json, true);

    // Check to verify keys are set then define local variable, 
    // or handle however you would normally in PHP.
    // If it isn't set we can either define a default value
    // ('' in this case) or do something else
    $action = (isset($parsedJSON['action'])) ? $parsedJSON['action'] : '';
    $par_1 = (isset($parsedJSON['par_1'])) ? $parsedJSON['par_1'] : '';
    $par_2 = (isset($parsedJSON['par_2'])) ? $parsedJSON['par_2'] : '';
    $par_3 = (isset($parsedJSON['par_3'])) ? $parsedJSON['par_3'] : '';

    // Or we could just use the array we have as is
    $sql = "UPDATE `table` SET 
                `par_1` = '" . $parsedJSON['par_1'] . "',
                `par_2` = '" . $parsedJSON['par_2'] . "',
                `par_3` = '" . $parsedJSON['par_3'] . "'
            WHERE `action` = '" . $parsedJSON['action'] . "'";
}

【讨论】:

    【解决方案2】:

    我确实认为拥有一个 RestClient 类可以更好地提高代码可扩展性,但基本上我认为你的代码对于基本解决方案来说是好的。在这里我发布了一个适当的 RestClient 类,它实现了一个 POST 或一个 GET:

    public class RestClient {
    
    private ArrayList<NameValuePair> params;
    private ArrayList<NameValuePair> headers;
    private String url;
    private String response;
    private int responseCode;
    
    public String GetResponse()
    {
        return response;
    }
    
    public int GetResponseCode()
    {
        return responseCode;
    }
    
    public RestClient(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }
    
    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }
    
    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }
    
    public void Execute(RequestType requestType) throws Exception
    {
        switch(requestType)
        {
            case GET:
            {
                String combinedParams = "";
                if (!params.isEmpty())
                {
                    combinedParams += "?";
                    for (NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
    
                        if  (combinedParams.length() > 1)
                            combinedParams += "&" + paramString;
                        else
                            combinedParams += paramString;
                    }
                }
                HttpGet request = new HttpGet(url + combinedParams);
    
                for (NameValuePair h: headers)
                    request.addHeader(h.getName(),h.getValue());
    
                ExecuteRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);
    
                for (NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }
    
                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }
    
                ExecuteRequest(request, url);
                break;
            }
        }
    }
    
    public void ExecuteRequest(HttpUriRequest request, String url) 
    {
        HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse;
        try
        {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
    
            HttpEntity entity = httpResponse.getEntity();
    
            if (entity != null)
            {
                InputStream in = entity.getContent();
                response = ConvertStreamToString(in);
                in.close();
            }
        }
        catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
            } catch (IOException e) {
            Log.e("REST_CLIENT", "Execute Request: " + e.getMessage()); 
            client.getConnectionManager().shutdown();
    
            e.printStackTrace();
        }       
    }
    
    private String ConvertStreamToString(InputStream in)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
    
        String line = null;
        try 
        {
            while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        finally 
        {
            try 
            {
                in.close();
            } 
            catch (IOException e) 
            {
                 Log.e("REST_CLIENT", "ConvertStreamToString: " + e.getMessage());  
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    

    有了这个,你可以很容易地做一个这样的 POST,例如:

    RestClient rest = new RestClient(url)
    rest.addHeader(h.name,h.value);
    rest.Execute(RequestType.POST);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2011-07-17
      相关资源
      最近更新 更多