如何在Android打开URL连接中将Json数组作为发布参数发送

时间:2019-06-18 07:10:42

标签: android arrays json httpurlconnection urlconnection

我必须使用Json数组的格式发出带有有效内容的发布请求。我正在使用开放的HTTP URL连接。我有使用url连接将Json对象作为post参数发送的代码,但我不知道如何发送json数组。下面显示的是用于json对象的打开url发布请求的代码。谁能帮我发送Json数组而不是json对象?

 public String   sendPostRequest(String arg0, JSONObject postDataParams){

    try {

        URL url = new URL(arg0); // here is your URL path

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Bearer Key");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));
        writer.flush();
        writer.close();
        os.close();

        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            BufferedReader in=new BufferedReader(new
                    InputStreamReader(
                    conn.getInputStream()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while((line = in.readLine()) != null) {

                sb.append(line);
                break;
            }

            in.close();
            return sb.toString();

        }
        else {
            return new String("false : "+responseCode);
        }
    }
    catch(Exception e){
        return new String("Exception: " + e.getMessage());
    }

}


// converting json object to encoded string

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

这是我要发布的格式。

[
  {
     "name":"CHV",
     "serialNumber":"421",
     "mac":"00:0d:83:b1:c0:8e",

  },
  {
     "name":"CHV_0",
     "serialNumber":"431",
     "mac":"50:0d:83:b1:c0:8e",
     }
   ]

如何更改代码以发布json数组。

1 个答案:

答案 0 :(得分:2)

此示例供您参考

String request = "your Url Here";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer Key");
conn.setRequestProperty("Content-Type", "application/json");

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);


JSONArray jsonArray=new JSONArray();
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
jsonArray.put(jsonParam);

wr.writeBytes(jsonArray.toString());

wr.flush();
wr.close();

有关更多详细信息,请参见hereherehere