Android BasicNameValuePair的值为JSONObject

3
我正在尝试向本地服务器发送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;
}

我想为参数创建一个键值对,格式为{"user": SOMEJSONObject},但是当前的HTTP POST只接受NameValuePair,它只能将值作为字符串传递。
1个回答

2
创建字符串实体代替:
httpPost.setEntity(new StringEntity("some string"));

1
请问能解释一下什么是实体(Entity)吗?"some string"是指Json字符串吗? - Doge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接