2011-08-24 193 views
132

我想在Java中使用JSON進行簡單的HTTP POST。在Java中使用JSON的HTTP POST

假設URL是www.site.com

,它需要在標註爲'details'例如價值{"name":"myname","age":"20"}

我該如何去創建POST的語法?

我也無法在JSON Javadoc中找到POST方法。

回答

19

這可能是最容易使用的HttpURLConnection

http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

您將使用的JSONObject或什麼來構建你的JSON,但不處理網絡;你需要序列化它,然後將它傳遞給HttpURLConnection以POST。

+0

JSONObject j = new JSONObject(); j.put(「name」,「myname」); j.put(「age」,「20」); 那樣?我如何序列化它? – asdf007

+0

@ asdf007只需使用'j.toString()'。 –

+0

但這個連接不是異步....儀式? – gumuruh

132

以下是你需要做的:

  1. 加深對Apache HttpClient的,這將使你做出了規定要求
  2. 創建一個與它的HttpPost請求,並添加標題爲「application/X- WWW的形式,進行了urlencoded」
  3. 創建StringEntity,您將通過JSON它
  4. 執行調用

釷E碼大致樣子(你仍需要調試它,讓它工作)

//Deprecated 
//HttpClient httpClient = new DefaultHttpClient(); 

HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 

try { 

    HttpPost request = new HttpPost("http://yoururl"); 
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); 
    request.addHeader("content-type", "application/x-www-form-urlencoded"); 
    request.setEntity(params); 
    HttpResponse response = httpClient.execute(request); 

    //handle response here... 

}catch (Exception ex) { 

    //handle exception here 

} finally { 
    //Deprecated 
    //httpClient.getConnectionManager().shutdown(); 
} 
+0

Super。這看起來很像我需要寫的東西。我試圖看看hc.apache.org/httpclient-3.x/上的Apache HttpClient,但它似乎是關閉了?哼。 – asdf007

+0

那麼我不需要一個JSONObject?我可以直接將String輸入到StringEntity中,如上所示並使用它? – asdf007

+6

你可以將它抽象爲JSONObject,好像你直接在字符串中進行抽象一樣,你可能會錯誤地編寫字符串並導致語法錯誤。通過使用JSONObject,您可以確保序列化始終遵循正確的JSON結構 – momo

29

@ MOMO的回答爲Apache HttpClient的,版本4.3.1或更高版本。我使用JSON-Java建立我的JSON對象:

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

謝謝,但不是「application/x-www-form-urlencoded」,內容類型應該是「應用程序/ json」! –

68

您可以使用GSON庫到您的Java類轉換成JSON對象。

創建要發送 按照以上示例

{"name":"myname","age":"20"} 

成爲

class pojo1 
{ 
    String name; 
    String age; 
    //generate setter and getters 
} 

一旦你設置pojo1類中的變量,你可以給變量一個POJO類,使用下面的代碼

String  postUrl  = "www.site.com";// put in your url 
Gson   gson   = new Gson(); 
HttpClient httpClient = HttpClientBuilder.create().build(); 
HttpPost  post   = new HttpPost(postUrl); 
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json 
post.setEntity(postingString); 
post.setHeader("Content-type", "application/json"); 
HttpResponse response = httpClient.execute(post); 

這些都是進口

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.HttpClientBuilder; 

和GSON

import com.google.gson.Gson; 
+0

嗨,你如何創建你的httpClient對象?這是一個接口 – user3290180

+1

是的,這是一個接口。您可以使用'HttpClient httpClient = new DefaultHttpClient()'創建一個實例;'' – Prakash

+1

現在已經棄用了,我們必須使用HttpClient httpClient = HttpClientBuilder.create()。build(); – user3290180

10

試試這個代碼:

HttpClient httpClient = new DefaultHttpClient(); 

try { 
    HttpPost request = new HttpPost("http://yoururl"); 
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); 
    request.addHeader("content-type", "application/json"); 
    request.addHeader("Accept","application/json"); 
    request.setEntity(params); 
    HttpResponse response = httpClient.execute(request); 

    // handle response here... 
}catch (Exception ex) { 
    // handle exception here 
} finally { 
    httpClient.getConnectionManager().shutdown(); 
} 
+0

謝謝!只有你的答案解決了編碼問題:) – Shrikant

+0

@SonuDhakar爲什麼你發送'application/json'既作爲accept頭和作爲內容類型 –

+0

似乎'DefaultHttpClient'已被棄用。 – sdgfsdh

5

我發現這個問題,尋找有關如何從Java客戶端發送POST請求,谷歌端點解決方案。以上答案很可能是正確的,但在Google Endpoint的情況下不起作用。

Google終端解決方案。

  1. 請求主體必須只包含JSON字符串,而不是名稱=值對。
  2. 內容類型標頭必須設置爲「application/json」。

    post("http://localhost:8888/_ah/api/langapi/v1/createLanguage", 
            "{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}"); 
    
    
    
    public static void post(String url, String param) throws Exception{ 
        String charset = "UTF-8"; 
        URLConnection connection = new URL(url).openConnection(); 
        connection.setDoOutput(true); // Triggers POST. 
        connection.setRequestProperty("Accept-Charset", charset); 
        connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); 
    
        try (OutputStream output = connection.getOutputStream()) { 
        output.write(param.getBytes(charset)); 
        } 
    
        InputStream response = connection.getInputStream(); 
    } 
    

    它肯定可以使用HttpClient來完成。

12
protected void sendJson(final String play, final String prop) { 
    Thread t = new Thread() { 
    public void run() { 
     Looper.prepare(); //For Preparing Message Pool for the childThread 
     HttpClient client = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit 
     HttpResponse response; 
     JSONObject json = new JSONObject(); 

      try { 
       HttpPost post = new HttpPost("http://192.168.0.44:80"); 
       json.put("play", play); 
       json.put("Properties", prop); 
       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(); 
       showMessage("Error", "Cannot Estabilish Connection"); 
      } 

      Looper.loop(); //Loop in the message queue 
     } 
    }; 
    t.start(); 
} 
+5

請考慮編輯您的帖子,以添加更多關於您的代碼的解釋以及爲什麼它可以解決問題。一個大多隻包含代碼的答案(即使它工作正常)通常不會幫助OP瞭解他們的問題 – Reeno

+1

這對我有效,謝謝! – Lozzano

+0

不用理睬 – Mohamed

0

我建議http-request它基於Apache HTTP API。

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class) 
    .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build(); 

public void send(){ 
    ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData); 

    int statusCode = responseHandler.getStatusCode(); 
    String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null. 
} 

如果你想發送JSON作爲請求體,您可以:

ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData); 

我使用前higly建議更換閱讀文檔。