在android中使用http post方法

时间:2014-07-04 10:01:36

标签: android

请建议我,如何使用http post方法。

我想将数据发送回PHP服务器,如下所示:

    {
  "customer_detail": {
    "customer_phone": "6774980865",
    "customer_comments": "Enter Your comments here...gvhhxjkjs",
    "customer_email": "prasanth@dunamis.com",
    "customer_name": "prasanth"
  },
  "feedBack": [
    {
      "qu_id": "1",
      "feedans": "Good"
    },
    {
      "qu_id": "2",
      "feedans": "Good"
    },
    {
      "qu_id": "3",
      "feedans": "Bad"
    },
    {
      "qu_id": "4",
      "feedans": "Bad"
    },
    {
      "qu_id": "5",
      "feedans": "Excellent"
    }
  ]
}

请给我解决方案。

1 个答案:

答案 0 :(得分:0)

使用此方法发出POST请求:

public String makePOSTRequest(String url, List<NameValuePair> nameValuePairs) {
    String response = "";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d(LOGTAG, "POST Response >>> " + response);
    return response;

}

用法:

在Java中:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsonObject.toString()));

String response = makePOSTRequest(String url, nameValuePairs );

服务器端Php:

$jsonInput = $_POST['json'];
json_decode($jsonInput);