HTTP POST using JSON in Java

前端 未结 11 993
南笙
南笙 2020-11-22 07:24

I would like to make a simple HTTP POST using JSON in Java.

Let\'s say the URL is www.site.com

and it takes in the value {\"name\":\"mynam

11条回答
  •  礼貌的吻别
    2020-11-22 08:08

    You can use the following code with Apache HTTP:

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

    Additionally you can create a json object and put in fields into the object like this

    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));
    

提交回复
热议问题