java发送post请求传json数据

511 阅读1分钟
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
 
 
 
//定义发送数据
JSONObject param = new JSONObject();
param.put("username", "zhangshan");
param.put("age", "18");
//定义接收数据
JSONObject result = new JSONObject();
 
String url = "http://www.baidu.com";
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
try {
    HttpResponse response = client.execute(httpPost);
    if (response.getStatusLine().getStatusCode() == 200) {
        result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
    }
} catch (IOException e) {
    e.printStackTrace();
    result.put("error", "连接错误!");
}

所需要的maven

<dependency>
        <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

测试类(无需maven的方式)

如果是放在测试类,则需要额外再加一个依赖jar包

例如如下的HttpPostTest.java:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
* @author qiuqiu_xqy
*/
public class HttpPostTest {

   public static void main(String[] args) {

       //定义发送数据
       JSONObject param = new JSONObject();
       param.put("username", "zhangshan");
       param.put("age", "18");
       //定义接收数据
       JSONObject result = new JSONObject();

       String url = "http://www.baidu.com";
       HttpPost httpPost = new HttpPost(url);
       CloseableHttpClient client = HttpClients.createDefault();
       //请求参数转JOSN字符串
       StringEntity entity = new StringEntity(param.toString(), "UTF-8");
       entity.setContentEncoding("UTF-8");
       entity.setContentType("application/json");
       httpPost.setEntity(entity);
       try {
           HttpResponse response = client.execute(httpPost);
           if (response.getStatusLine().getStatusCode() == 200) {
               result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
           }
       } catch (IOException e) {
           e.printStackTrace();
           result.put("error", "连接错误!");
       }
   }
}