java - 以 JSONObject 作为值的 Android BasicNameValuePair

标签 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;
}

对于参数,我想创建一个值对作为 {"user": SOMEJSONObject} 但当前的 http POST 只接受 NameValuePair,它只接受字符串作为值。

最佳答案

改为创建字符串实体:

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

关于java - 以 JSONObject 作为值的 Android BasicNameValuePair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21686424/

相关文章:

java - 对于大量数据,是否有替代 AtomicReferenceArray 的方法?

android - 如何退出 firebase

json - 在 GoLang 中将 JSON 目录树转换为缩进纯文本

java - 带有嵌套 JSON 的 REST

java - windows和linux之间FTP传输时不同的路径分隔符

java - html 中搜索的正则表达式

java - 它显示客户已定义的错误。请让我知道发生了什么错误以及如何纠正它

android - 如何在 android 中为媒体播放器开发自定义均衡器?

从 MIC 读取 android AudioRecord 振幅

json - 如何使用 mustache 呈现 JSON 模板