簡體   English   中英

Android BasicNameValuePair,以JSONObject作為值

[英]Android BasicNameValuePair with JSONObject as value

我正在嘗試將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,它只接受值的字符串。

改為創建String實體:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM