2017-08-25 52 views
1

我正在使用Jersey客戶端來執行請求。這是一個例子。如何使用Jersey 2.26客戶端使用queryParam執行HTTP POST請求?

https://myschool.com/webapi/rest/student/submitJob?student={student:[{"id":1,"name":"Tom","age":20},{"id":2,"name":"Bob","age":20}]}&score={score:[{"id":1,"math":90,"art":80,"science":70},{"id":2,"math":70,"art":60,"science":80}]} 

而他們的迴應是這樣的: { 「的jobId」: 「123456789」, 「jobStatus」: 「JobSubmitted」}

這是我當前的代碼:

String student = {student:[{"id":1,"name":"Tom","age":20},{"id":2,"name":"Bob","age":20}]}; 
String score = {score:[{"id":1,"math":90,"art":80,"science":70},{"id":2,"math":70,"art":60,"science":80}]} 

String responseResult = client.target("https://myschool.com/webapi/rest/student/").path("submitJob") 
         .queryParam("student", student).queryParam("score", score).request("application/json").get(String.class); 

問題是真正的請求URI太長,我得到了414錯誤。所以我需要使用POST而不是GET方法。但我使用queryParam發送請求,但不是Body。誰能告訴我該怎麼做?謝謝。

回答

0

此代碼是基於來自@MohammedAbdullah的回答以及澤西文檔的靈感。

Client client = ClientBuilder.newClient(); 
WebTarget target = client.target("https://myschool.com/webapi/rest/student/").path("submitJob"); 
Form form = new Form(); 
form.param("student", student); 
form.param("score", score); 
String responseResult = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); 
0
Use POST Method and Set Content type as "application/x-www-form-urlencoded". POST method increases allowable url request limit. 


String student = {student:[{"id":1,"name":"Tom","age":20},{"id":2,"name":"Bob","age":20}]}; 
String score = {score:[{"id":1,"math":90,"art":80,"science":70},{"id":2,"math":70,"art":60,"science":80}]}; 
Client client = ClientBuilder.newClient(); 
Form input = new Form(); 
input.param("student", student); 
input.param("score", score); 
Entity<Form> entity = Entity.entity(input, MediaType.APPLICATION_FORM_URLENCODED); 
String url = "https://myschool.com/webapi/rest/student/submitJob"; 
ClientResponse response = client.target.request(MediaType.APPLICATION_JSON_TYPE) 
.post(entity); 
+0

當我試過你的代碼時,在最後一行代碼中出現了「資源(url)」錯誤。也許我有誤解,你能解釋一下嗎? @MohammedAbdullah – ZLi

+0

請立即檢查。 –

+0

錯誤消息:「方法資源()未定義類型客戶端」。 @MohammedAbdullah – ZLi

相關問題