2011-08-24 40 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建议更换阅读文档。