如何使用 android 中的 HttpsURLConnection 在 url 中将 json 对象作为请求参数发送

How to send json object as request parameter in a url using HttpsURLConnection in android

我有一个 url 作为 https://www.xyz.in/ws/bt,请求参数为令牌、块请求和格式。 示例 JSON “blockrequest” 字符串为


{"source\":\"1492\",\"destination\":\"1406\",\"availableTripId\":\"100008417320611112\",\"boardingPointId\":\"1129224\",\"inventoryItems\":[{\"seatName\":\"21\",\"ladiesSeat\":\"false\",\"passenger\":{\"name\":\"passenger_name_1\",\"title\":\"MR\",\"gender\":\"MALE\",\"age\":\"23\",\"primary\":true,\"idType\":\"PANCARD\",\"email\":\"pass_name@domain_name.com\",\"idNumber\":\"BEPS1111B\",\"address\":\"passenger_address\",\"mobile\":\"xxxxxxxxxx\"},\"fare\":\"320.00\"},{\"seatName\":\"22\",\"ladiesSeat\":\"true\",\"passenger\":{\"name\":\"passenger_name_1\",\"title\":\"MS\",\"gender\":\"FEMALE\",\"age\":\"23\",\"primary\":false,\"idType\":\"\",\"email\":\"\",\"idNumber\":\"\",\"address\":\"\",\"mobile\":\"\"},\"fare\":\"320.00\"}]}

如何使用 HttpsURLConnection 在 url 中将此数据作为 请求参数 发送。

如果您使用 Apache HTTP 客户端。这是一个代码示例

protected void send(final String json) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;

                try {
                    HttpPost post = new HttpPost(URL);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

这是上面示例代码中的 imp 行:

StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);  

尝试this.I希望它有效。

你可以这样做:

URL url = new URL(yourUrl);
byte[] postData = yourJsonString.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.getOutputStream().write(postDataBytes);

(要读取响应,请使用连接的 getInputStream() 方法)