2016-06-01 108 views
0

我有一个url作为https://www.xyz.in/ws/bt与请求参数作为标记,blockrequest和格式。 样品JSON“blockrequest”字符串如何发送json对象作为请求参数在URL中使用HttpsURLConnection android


{"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\":\"[email protected]_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发送这个数据作为请求参数

+0

带有“请求参数”你的意思是HTTP GET请求? – Robert

+0

不,通过HTTPS POST请求。 – QEMU

+1

http://stackoverflow.com/a/2938787/793943检查这个答案 – Sush

回答

0

如果您使用Apache HTTP Client。下面是一个代码示例

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();  
    } 

这是上面的示例代码小鬼行:

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

尝试this.I希望它的工作。

+0

已弃用Apache HTTP客户端已在API 23(Android 6)中删除。 – Robert

+0

使用排气库代替 –

+0

是的。使用凌空或改造。所以你可以根据请求轻松发送json主体。 –

0

你可以做这样的事情:

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()法)

相关问题