2016-05-31 135 views
1

我想要將json發送到查詢參數中的GET請求以獲取該json請求的響應。如何將json添加到GET請求查詢參數?

如果我使用一個鏈接是這樣的:

www.url.com/search?query1=abc &過濾器= { 「或」:[{ 「術語」:{ 「VIN」: 「1g1105sa2gu104086」]}}]}

然後URL部分顯示爲藍色,如果我做它作爲系統輸出語句,像這樣:

www.url.com/search?query1=abc&過濾器= { 「或」:[{「條款「:{」vin「:[」1g1105sa2gu104086「]}}]}

和json看起來好像它不是請求的一部分。

要創建一個URL,我將操作的JSON字符串附加到URL,然後發送請求。但它表現爲兩個不同的字符串。

另外我已經使用編碼器到JSON部分編碼

濾波器= { 「或」:[{ 「術語」:{ 「VIN」:[ 「1g1105sa2gu104086」]}}]}

在這種情況下,括號和雙引號該json中的所有內容都被編碼,即使是equalTo符號。此外,該鏈接顯示爲藍色,但在發送請求時,會拋出400錯誤請求的異常,因爲equalTo也會轉換爲其編碼格式。

我試圖編碼只有JSON部分離開filter=在URL中,這樣的事情:

www.url.com/search?query1=abc&filter= { 「或」:[{ 「術語」:{ 「VIN」: 「1g1105sa2gu104086」 ]}}]}

請求發送後出現的結果與我想要的結果不同。

我用下面的代碼創建一個JSON:

private String getVinFromInventoryRequest(String vin) throws JSONException { 
    JSONObject request = new JSONObject(); 
    JSONArray orArray = new JSONArray(); 
    for(String vin : vins) { 
     JSONObject termsObject = new JSONObject(); 
     JSONObject vinsObject = new JSONObject(); 
     JSONArray vinsArray = new JSONArray(); 
     vinsArray.put(vin); 
     vinsObject.put("vin", vinsArray); 
     termsObject.put("terms", vinsObject); 
     orArray.put(termsObject); 
    } 
    request.put("or", orArray); 
    System.out.println("OfferMapper.getVinFromInventoryRequest " + request.toString()); 
    return request.toString(); 
} 
+0

怎麼辦你編碼的JSON?該編碼的結果是什麼?你能提供例子嗎? – Mark

+0

重複的:http://stackoverflow.com/questions/23476033/how-should-i-put-json-in-get-request –

+0

我使用URLEncoder在Java中編碼json。它以這種格式編碼:過濾器%3D%7B%22和%22%3A%5B%7B%22%22%3A%7B%22%%22%3A%5B%221g1105sa2gu104086%22%5D%7D%7D%5D %7D –

回答

0

也期待什麼,我發現有一點谷歌搜索:

JSONObject json = new JSONObject(); 
json.put("someKey", "someValue");  

CloseableHttpClient httpClient = HttpClientBuilder.create().build(); 

try { 
    HttpPost request = new HttpPost("http://yoururl"); 
    StringEntity params = new StringEntity(json.toString()); 
    request.addHeader("content-type", "application/json"); 
    request.setEntity(params); 
    httpClient.execute(request); 
// handle response here... 
} catch (Exception ex) { 
    // handle exception here 
} finally { 
    httpClient.close(); 
} 

欲瞭解更多信息,請參閱:HTTP POST using JSON in Java

相關問題