JAVA-HttpClient发送post get 请求 设置请求头

1:import

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

 

2: POST请求

 public static String sendPost(String url, String sign, String timeStamp) {
    
        HttpClient httpClient;
        HttpPost postMethod;
        HttpResponse response;
        String reponseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            postMethod = new HttpPost(url);
            //postMethod.addHeader("Content-type", "application/json; charset=utf-8");
            //设置请求头
            postMethod.addHeader("Content-type", "text/plain;charset=utf-8");
            postMethod.addHeader("accept", "*/*");
            postMethod.addHeader("connection", "Keep-Alive");
            postMethod.addHeader("sign", sign);
            postMethod.addHeader("timeStamp", timeStamp);
            postMethod.setEntity(new StringEntity("", Charset.forName("UTF-8")));
            response = httpClient.execute(postMethod);
            HttpEntity httpEntity = response.getEntity();
            reponseContent = EntityUtils.toString(httpEntity);
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reponseContent;
    }

3: GET请求

 public static String AccountCenter(String url, String Authorization) throws Exception {
        HttpClient httpClient;
        HttpGet postMethod;
        HttpResponse response;
        String reponseContent;
        httpClient = HttpClients.createDefault();
        postMethod = new HttpGet(url);
        postMethod.addHeader("Content-type", "text/plain;charset=utf-8");
        postMethod.addHeader("accept", "*/*");
        postMethod.addHeader("connection", "Keep-Alive");
        postMethod.addHeader("Authorization", "Bearer " + Authorization);
        response = httpClient.execute(postMethod);
        HttpEntity httpEntity = response.getEntity();
        reponseContent = EntityUtils.toString(httpEntity);
        EntityUtils.consume(httpEntity);
        return reponseContent;
    }

 

你可能感兴趣的:(编程语言Java)