zoukankan      html  css  js  c++  java
  • java http/https post/get 请求 ,携带header参数

    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)
     
  • 相关阅读:
    60、剑指offer--把二叉树打印成多行
    59、剑指offer--按之字形顺序打印二叉树
    KNN(最近邻算法)
    RBM(受限玻尔兹曼机)
    Denoising Autoencod
    决策树算法
    AdaBoost算法简介
    suricata工作流程简介
    KD tree详解
    tesseract训练新字库
  • 原文地址:https://www.cnblogs.com/remember-forget/p/14840145.html
Copyright © 2011-2022 走看看