【问题标题】:How to send Json array as post params in android open URL connection如何在 android 打开 URL 连接中将 Json 数组作为 post 参数发送
【发布时间】:2019-06-18 07:10:42
【问题描述】:

我必须使用 Json 数组格式的有效载荷发出一个 post 请求。我正在使用开放的 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 数组。

【问题讨论】:

    标签: android arrays json httpurlconnection urlconnection


    【解决方案1】:

    此示例供您参考

    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

    【讨论】:

    • 这是发送json对象。但在这里我必须发布。子数组,其中包含 json 对象。该 api 将只接受 json 数组。如果我尝试发送一个 json 对象,它会给我一个 400 异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多