Android BasicNameValuePair,以JSONObject作为值

时间:2014-02-10 19:42:03

标签: java android json http http-post

我正在尝试将http POST请求发送到本地服务器

这是代码:

public JSONObject makeHttpRequest (String url, String method, List<NameValuePair> params) {
    try {
        if (method == "POST") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            httpStatusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();
            inputStream = httpEntity.getContent();
        } else if (method == "GET") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            httpStatusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();
            inputStream = httpEntity.getContent();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        inputStream.close();
        jsonString = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        jsonObject = new JSONObject(jsonString);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data" + e.toString());
    }
    return jsonObject;
}

对于param我想创建一个值对{{user“:SOMEJSONObject}但是当前的http POST只接受NameValuePair,它只接受值的字符串。

1 个答案:

答案 0 :(得分:2)

改为创建字符串实体:

httpPost.setEntity(new StringEntity("some string"));