java调用httpclient提交post请求,参数为json

import org.apache.http.*;
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;
 
//模拟浏览器发送http请求完成固定地址的请求
public class HttpClientUtils {
     
    public static void main(String[] args){
        String url = "http://localhost:8080/*";
        String json = "{\"a\":\"aa\",\"b\":\"bb\",\"c\":\"cc\"}";        
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        String response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());
                response = result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return;
    }
}
 


版权声明:本文为daqinzl原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。