在Java中使用JSON的HTTP POST

asd*_*007 176 java post json http

我想在Java中使用JSON进行简单的HTTP POST.

我们说URL是 www.site.com

并且它采用{"name":"myname","age":"20"}标记'details'为例如的值.

我将如何创建POST的语法?

我似乎也无法在JSON Javadocs中找到POST方法.

mom*_*omo 159

这是你需要做的:

  1. 获取Apache HttpClient,这将使您能够提出所需的请求
  2. 用它创建一个HttpPost请求并添加标题"application/x-www-form-urlencoded"
  3. 创建一个StringEntity,您将JSON传递给它
  4. 执行通话

代码大致看起来像(你仍然需要调试它并让它工作)

//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(); 
}
Run Code Online (Sandbox Code Playgroud)

  • 内容类型不应该是'application/json'.'application/x-www-form-urlencoded'表示字符串的格式类似于查询字符串.NM我看到你做了什么,你把json blob作为属性的值. (12认同)
  • 你可以但最好将它抽象为JSONObject,就像你直接在字符串中进行一样,你可能会错误地编写字符串并导致语法错误.通过使用JSONObject,您可以确保序列化始终遵循正确的JSON结构 (9认同)
  • 原则上,它们都只是传输数据.唯一的区别是你如何在服务器中处理它.如果你只有很少的键值对,那么一个普通的POST参数,其中key1 = value1,key2 = value2等就足够了,但是一旦你的数据更加复杂,特别是包含复杂的结构(嵌套对象,数组),你会想要开始考虑使用JSON.使用键值对发送复杂的结构将是非常讨厌并且难以在服务器上解析(您可以尝试并且您将立即看到它).还记得我们不得不这样做的那一天..它不漂亮.. (3认同)

Pra*_*ash 89

您可以使用Gson库将您的Java类转换为JSON对象.

按照上面的示例为要发送的变量创建一个pojo类

{"name":"myname","age":"20"}
Run Code Online (Sandbox Code Playgroud)

class pojo1
{
   String name;
   String age;
   //generate setter and getters
}
Run Code Online (Sandbox Code Playgroud)

一旦你在pojo1类中设置变量,你可以使用以下代码发送它

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);
Run Code Online (Sandbox Code Playgroud)

这些是进口

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;
Run Code Online (Sandbox Code Playgroud)

而对于GSON

import com.google.gson.Gson;
Run Code Online (Sandbox Code Playgroud)

  • 如何导入HttpClientBuilder? (5认同)
  • 我发现在StringUtils构造函数上使用ContentType参数并传入ContentType.APPLICATION_JSON而不是手动设置标题会稍微清晰一些. (3认同)
  • 现在已经弃用了,我们必须使用HttpClient httpClient = HttpClientBuilder.create().build(); (2认同)

Leo*_*lva 43

@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();
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ill 20

使用HttpURLConnection可能最简单.

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

您将使用JSONObject或其他任何内容构建您的JSON,但不能处理网络; 你需要序列化它,然后将它传递给HttpURLConnection进行POST.


小智 14

试试这段代码:

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();
}
Run Code Online (Sandbox Code Playgroud)


Med*_*edo 14

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 请考虑编辑您的帖子,以添加有关您的代码的功能以及解决问题的原因的更多说明.一个主要只包含代码的答案(即使它正在工作)通常无助于OP理解他们的问题 (7认同)
  • @Reeno这段代码几乎是自我解释的 (2认同)

yur*_*rin 10

我发现这个问题正在寻找有关如何从Java客户端向Google端点发送帖子请求的解决方案.以上答案,很可能是正确的,但在Google端点的情况下无效.

Google端点解决方案.

  1. 请求正文必须只包含JSON字符串,而不是name = value对.
  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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

    确定也可以使用HttpClient来完成.


TMO*_*TMO 6

您可以将以下代码用于Apache HTTP:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

response = client.execute(request);
Run Code Online (Sandbox Code Playgroud)

另外,您可以创建一个json对象,并像这样将字段放入对象

HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)


小智 6

对于 Java 11,您可以使用新的HTTP 客户端

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://localhost/api"))
    .header("Content-Type", "application/json")
    .POST(ofInputStream(() -> getClass().getResourceAsStream(
        "/some-data.json")))
    .build();

client.sendAsync(request, BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .join();
Run Code Online (Sandbox Code Playgroud)

您可以使用来自InputStreamString、 的发布者File。可以使用 Jackson将 JSON 转换为 aStringIS