发布列表<list <namevaluepair>&gt;在makehttprequest JSONParser中

时间:2016-11-23 07:32:34

标签: java android

目前使用以下内容在webpack中的makehttprequest中发布List<NameValuePair>。现在需要通过JSONParser。我已经得到了以下代码,需要创建新函数来传递List<List<NameValuePair>>

List<List<NameValuePair>>

1 个答案:

答案 0 :(得分:1)

使用 DefaultHttpClient, HttpPost, HttpResponse, HttpEntity and NameValuePair 是一个坏主意,因为所有这些都已弃用,所以我们不应该使用它。 现在您应该使用 HttpURLConnection StringBuilder, Map 将数据发送到服务器:

protected JSONArray getResult(URL url, Map<String, Object> urlParams {
    HttpURLConnection conn;
    BufferedReader in;
    String line;
    StringBuilder chaine = new StringBuilder();
    StringBuilder postData = new StringBuilder();
    byte[] postDataBytes = new byte[0];

    // urlParams = Map<String, Object>
    for (Map.Entry<String, Object> param : urlParams.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        try {
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            postDataBytes = postData.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
    try { 
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));

        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = in.readLine()) != null) {
            chaine.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONArray result = null;
    try {
        result = new JSONArray(chaine.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.e("DATABASE_REST Result", result.toString());
    return result;
}

因此,如果存在类似于对象的地图,则可以使用下一个地图