码迷,mamicode.com
首页 > 编程语言 > 详细

java http/https post/get 请求 ,携带header参数

时间:2021-06-02 20:58:50      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:cep   fas   type   bsp   methods   org   throw   get   dog   

import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

public class HttpPostJsonUtil {

    public static JSONObject doPost(String url, JSONObject jsonObject) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        post.addHeader("Content-type","application/json; charset=utf-8");
        post.setHeader("Accept", "application/json");

        try {
            post.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(entity);
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }

    public static JSONObject doGet(String url) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        JSONObject response = null;
        get.addHeader("Content-type","application/json; charset=utf-8");
        get.setHeader("Accept", "application/json");

        try {
            HttpResponse res = client.execute(get);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(entity);
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }

}

 方法中,jsonObject 参数可以换成 list 或者 map ,只要将 

jsonObject.toString() 换成
JSONObject.toJSONString(list) 或者
JSONObject.toJSONString(map)
 

java http/https post/get 请求 ,携带header参数

标签:cep   fas   type   bsp   methods   org   throw   get   dog   

原文地址:https://www.cnblogs.com/remember-forget/p/14840145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!