天天看点

后端发送HTTP请求后端发送HTTP请求

后端发送HTTP请求

1 原始方式

背景:

get:获取微信的accessToken

post:设置微信公众号的自定义菜单

1.1 get方式

//get方式发起请求
public String get(String url){
    try{
        URL urlObj = new URL(url);
        //开连接
        URLConnection connection = urlObj.openConnection();
        InputStream is = connection.getInputStream();
        byte[] b = new byte[1024];
        int len;
        StringBuilder stb = new StringBuilder();
        while((len=is.read(b)) != -1){
            stb.append(new String(b, 0, len));
        }
        return stb.toString();
    } catch (Exception e){
        e.printStackTrace();
    }
    return null;
}
           

1.2 post方式

//post方式发起请求,data是请求体
public static String post(String url, String data){
    try{
        URL urlObj = new URL(url);
        URLConnection connection = urlObj.openConnection();
        //要发送数据出去,必须要设置为可发送数据状态
        connection.setDoOutput(true);
        //获取输出流
        OutputStream os = connection.getOutputStream();
        //写出数据
        os.write(data.getBytes());
        os.close();
        //获取输入流
        InputStream is = connection.getInputStream();
        byte[] b = new byte[1024];
        int len;
        StringBuilder stb = new StringBuilder();
        while((len = is.read(b)) != -1){
            stb.append(new String(b, 0, len));
        }
        return stb.toString();
    } catch (Exception e){
        e.printStackTrace();
    }
    return null;
}
           

2 使用OKHttp

导入依赖:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.8.0</version>
</dependency>
           

2.1 基本方式

①通过get方式

public void OkHttpGet(String url) {
    OkHttpClient okHttpClient = new OkHttpClient();
    //不配url方法会报错,肯定要有访问地址的嘛
    //.Builder是Request内部类 .url()返回Builder .build()返回Request对象
    Request request = new Request.Builder()
            //.addHeader("a", "b")//.addHeader添加键值对header信息
            //.get()//可加可不加
            .url(url)
            .build();
    Call call = okHttpClient.newCall(request);
    try {
        Response response = call.execute();
        System.out.println(response.body().string());
        //http状态码
        System.out.println(response.code());
        //response的头信息
        System.out.println(response.headers().toString());
        //请求响应时间,收到时间减去发送的时间,单位毫秒
        System.out.println(response.receivedResponseAtMillis()-response.sentRequestAtMillis());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
           

②通过post方式

public void OkHttpPost(String url){
     //ssl认证重写
    OkHttpClient okHttpClient=new OkHttpClient.Builder().hostnameVerifier(
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            }
    ).build();
    RequestBody requestBody=new FormBody.Builder()
            .add("oldPassword","111111")
            .add("newPassword","111111")
            .build();

    Request request=new Request.Builder()
            .url(url)
            .post(requestBody)
            .addHeader("Cookie","JSESSIONID=299571E0E40DA6E9962E41B87A669BBB")
            .addHeader("content-type", "application/json")
            .addHeader("cache-control", "no-cache")
            .build();
    Call call=okHttpClient.newCall(request);

    try {
        Response response=call.execute();
        System.out.println(response.body().string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
           

2.2 封装OKHttp

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class OkHttpUtil {

    /**
     * Get请求
     * @param url   URL地址
     * @return  返回结果
     */
    public static String get(String url){
        String result=null;
        try {
            OkHttpClient okHttpClient=new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = okHttpClient.newCall(request).execute();
            result=response.body().string();
            log.info("Get请求返回:{}",result);
            return result;
        }catch (Exception e){
            log.error("OkHttp[Get]请求异常",e);
            return result;
        }
    }

    /**
     * Post请求
     * @param url       URL地址
     * @param params    参数
     * @return  返回结果
     */
    public static String post(String url,Map<String,String> params){
        String result=null;
        if (params==null){
            params=new HashMap<String, String>();
        }
        try {
            OkHttpClient okHttpClient=new OkHttpClient();
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            //添加参数
            log.info("params:{}", JSON.toJSONString(params));
            for (Map.Entry<String,String> map:params.entrySet()){
                String key=map.getKey();
                String value;
                if (map.getValue()==null){
                    value="";
                }else{
                    value=map.getValue();
                }
                formBodyBuilder.add(key,value);
            }
            FormBody formBody =formBodyBuilder.build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            Response response = okHttpClient.newCall(request).execute();
            result=response.body().string();
            log.info("Post请求返回:{}",result);
            return result;
        }catch (Exception e){
            log.error("OkHttp[Post]请求异常",e);
            return result;
        }
    }

    /**
     * 上传文件请求(Post请求)
     * @param url       URL地址
     * @param params    文件 key:参数名 value:文件 (可以多文件)
     * @return  返回结果
     */
    public static String upload(String url, Map<String, File> params){
        String result=null;
        try {
            OkHttpClient okHttpClient=new OkHttpClient();
            MultipartBody.Builder multipartBodyBuilder =new MultipartBody.Builder().setType(MultipartBody.FORM);

            for (Map.Entry<String,File> map:params.entrySet()){
                String key=map.getKey();
                File file=map.getValue();
                if (file==null||(file.exists() && file.length() == 0)){
                    continue;
                }
                multipartBodyBuilder.addFormDataPart(key,file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"), file));
            }
            RequestBody requestBody =multipartBodyBuilder.build();
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Response response = okHttpClient.newCall(request).execute();
            result=response.body().string();
            log.info("Upload请求返回:{}",result);
            return result;
        }catch (Exception e){
            log.error("OkHttp[Upload]请求异常",e);
            return result;
        }
    }

    /**
     * 下载文件请求(Get请求)
     * @param url       URL地址
     * @param savePath  保存路径(包括文件名)
     * @return  文件保存路径
     */
    public static String download(String url,String savePath){
        String result=null;
        try {
            OkHttpClient okHttpClient=new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = okHttpClient.newCall(request).execute();
            File file=new File(savePath);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            BufferedSink sink =Okio.buffer((Okio.sink(file)));
            sink.writeAll(response.body().source());
            sink.flush();
            sink.close();
            result=savePath;
            log.info("Download请求返回:{}",result);
            return result;
        }catch (Exception e){
            log.error("OkHttp[Download]请求异常",e);
            return result;
        }
    }

}
           

2.3 OKHttp的post方式详解

①基本的post请求,包含参数

/**
  * post请求的body中带有参数
  */
 @Test
 public void postWithBody() throws IOException {
     //构建请求的body
     RequestBody body = new FormBody.Builder()
             .add("username", "zhangsan")
             .add("password", "123456")
             .build();

     //构建请求
     Request request = new Request.Builder()
             .url(base_url + "testOkHttpByPost")
             .post(body)
             .build();
     Call call = client.newCall(request);
     Response response = call.execute();
     Assert.assertEquals(response.code(), 200);
 }
           
//post请求的body中带有参数
@PostMapping("/testOkHttpByPost")
public void testOkHttpByPost(HttpServletRequest request) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
        System.out.println(entry.getKey());
        String[] value = entry.getValue();
        System.out.println(Arrays.toString(value));
    }
}
           

②post请求带有授权

/**
 * post请求带有授权的
 */
@Test
public void postWithAuth() throws IOException {
    String postBody = "test post auth";
    Request request = new Request.Builder()
            .url(base_url + "testOkHttpByAuth")
            .addHeader("Authorization", "Messi")
            .post(RequestBody.create(
                    MediaType.parse("text/x-markdown"), postBody))
            .build();
    Call call = client.newCall(request);
    Response response = call.execute();
    Assert.assertEquals(response.code(), 200);
}
           
//post请求中带有身份验证
@PostMapping("/testOkHttpByAuth")
public void testOkHttpByAuth(HttpServletRequest request, @RequestBody String text){
    String authorization = request.getHeader("Authorization");
    if("Messi".equals(authorization)){
        System.out.println("success...");
    }else {
        System.out.println("fail....");
    }
    System.out.println(text);//test post auth
}
           

③post请求中带有json数据

/**
  * post向请求体中发送json数据
  */
 @Test
 public void postByJson() throws IOException {
     String json = "{\n" +
             "    \"username\":\"laowang\",\n" +
             "    \"age\":18\n" +
             "}";
     //为了在请求体中发送json,需要设置媒体类型为application/json
     RequestBody body = RequestBody.create(
             MediaType.parse("application/json"),json);
     Request request = new Request.Builder()
             .url(base_url + "/postByJson")
             .post(body)
             .build();
     Call call = client.newCall(request);
     Response response = call.execute();
     Assert.assertEquals(response.code(), 200);
 }
           
//post请求体带有json数据
@PostMapping("/postByJson")
public void testOkHttpByJson(@RequestBody String json){
    System.out.println(json);
}
           

④发送Multipart post

/**
 * 发送 Multipart post请求
 */
@Test
public void postByMultipart() throws IOException {
    RequestBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", "wangchen")
            .addFormDataPart("password", "123456")
            .addFormDataPart("file", "file.txt",
                    RequestBody.create(MediaType.parse("application/octet-stream"),
                            new File("src/main/resources/text.txt")))
            .build();

    Request request = new Request.Builder()
            .url(base_url + "/postMultipart")
            .post(body)
            .build();

    Call call = client.newCall(request);
    Response response = call.execute();
    Assert.assertEquals(response.code(), 200);
}
           
//发送Multipart post
@PostMapping("/postMultipart")
public void testOkHttpMultipart(String username, String password, MultipartFile file){
    System.out.println(username);
    System.out.println(password);
    String originalFilename = file.getOriginalFilename();
    System.out.println(originalFilename);
}
           

⑤修改编码格式

//通过其他方式编码
 //如果我们想使用其他字符编码,我们可以将其作为 MediaType.parse () 的第二个参数传入:
 @Test
 public void postByOtherEncoding(){
     String json = "{\n" +
             "    \"username\":\"laowang\",\n" +
             "    \"age\":18\n" +
             "}";
     RequestBody body = RequestBody.create(
             MediaType.parse("application/json;charset=UTF-8"), json);

     String charset = body.contentType().charset().displayName();
     Assert.assertEquals(charset, "UTF-16");
 }
           

2.4 OKHttp发起同步异步请求

2.4.1 同步发送get请求

/**
  * get请求【同步方式】
  * @param url
  * @return
  */
 public static Response getWithNoParam(String url){
     Response result = null;
     try{
         //设置5s超时
         OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
         //请求
         Request request = new Request.Builder().url(url).build();
         System.out.println("request.headers() = " + request.headers().toString());
         System.out.println(">>>>>>>>>>>" + request.headers().get("Host"));
         //响应
         Response response = client.newCall(request).execute();
         //获取响应体内容
         result = response;
         return result;
     } catch (Exception e){
         log.error("get请求异常:{}", e);
         return result;
     }
 }




/**
 * 同步发送get请求【添加参数】
 * @param url
 * @param paramMap
 * @return
 */
public static Response getWithParams(String url, Map<String, String> paramMap){
    Request.Builder requestBuilder = new Request.Builder();
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    String key = "";
    String value = "";
    for(Map.Entry<String, String> entry : paramMap.entrySet()){
        key = entry.getKey();
        value = entry.getValue();
        urlBuilder.addQueryParameter(key, value);
    }
    requestBuilder.url(urlBuilder.build());
    Request request = requestBuilder.build();
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
    Call call = client.newCall(request);
    Response response = null;
    try {
        response = call.execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}
           

2.4.2 异步发送get请求

/**
 * 异步发起get请求
 * @param url
 */
public static void getByAsync(String url){
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
    Request request = new Request.Builder().url(url).get().build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            //请求失败之后所作操作...
            System.out.println("fail.....");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            //请求成功之后所做操作....异步请求成功之后的回调,例如:txtView.setText(response.body().string ());
            System.out.println(response.body().string());
        }
    });
}
           

3 使用HttpClient

3.1 发送基本请求

//创建连接[同步连接]
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//    CloseableHttpClient client = HttpClients.createDefault();//创建默认client【与上面没有区别】

//创建连接【异步】
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClientBuilder.create().build();

private String uri_prefix = "http://localhost:8080/";
           

①get方式

//get请求
    @Test
    public void testGet() throws IOException {
        String url = uri_prefix + "testGet";
        HttpGet httpGet = new HttpGet(url);
        //给请求头设置值【get也可以通过拼接URL来传递参数】
        httpGet.setHeader("token", "fadsofafa");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        System.out.println(response.getEntity());
    }
           

②put方式

//put请求
@Test
public void testPut() throws IOException {
    String api = "testPut";
    String url = uri_prefix + api;
    HttpPut httpPut = new HttpPut(url);
    //要传输的json数据【标准写法应该通过对象传输,然后转换为json串】
    String json = "{\n" +
            "    \"username\":\"laowang\",\n" +
            "    \"age\":18\n" +
            "}";
    //传输json数据,修改request头信息
    httpPut.setHeader("Content-Type", "application/json;charset=utf8");
    //设置传输的json
    httpPut.setEntity(new StringEntity(json, "UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPut);
    System.out.println(EntityUtils.toString(response.getEntity()));
}
           

③post

//post请求[与put方式无太多区别]
@Test
public void testPost() throws IOException {
    String api = "testPost";
    String url = uri_prefix + api;
    HttpPost httpPost = new HttpPost(url);
    String json = "{\n" +
            "    \"username\":\"laowang\",\n" +
            "    \"age\":18\n" +
            "}";
    httpPost.setHeader("Content-Type", "application/json;charset=utf8");
    //设置具体数据
    httpPost.setEntity(new StringEntity(json, "UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    System.out.println(response.getEntity());
}
           

④delete

//测试delete
@Test
public void testDelete() throws IOException {
    String api = "testDelete";
    String url = uri_prefix + api;
    HttpDelete httpDelete = new HttpDelete(url);
    CloseableHttpResponse response = httpClient.execute(httpDelete);
    System.out.println(EntityUtils.toString(response.getEntity()));
}
           
其他同理

3.2 工具类HttpClientUtils

public class HttpClientUtils {

    public static final int connTimeout=10000;
    public static final int readTimeout=10000;
    public static final String charset="UTF-8";
    private static HttpClient client = null;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
        return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
    }

    public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
        return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
            SocketTimeoutException, Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
            SocketTimeoutException, Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String get(String url) throws Exception {
        return get(url, charset, null, null);
    }

    public static String get(String url, String charset) throws Exception {
        return get(url, charset, connTimeout, readTimeout);
    }

    /**
     * 发送一个 Post 请求, 使用指定的字符集编码.
     *
     * @param url
     * @param body RequestBody
     * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
     * @param charset 编码
     * @param connTimeout 建立链接超时时间,毫秒.
     * @param readTimeout 响应超时时间,毫秒.
     * @return ResponseBody, 使用指定的字符集编码.
     * @throws ConnectTimeoutException 建立链接超时异常
     * @throws SocketTimeoutException  响应超时
     * @throws Exception
     */
    public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
            throws ConnectTimeoutException, SocketTimeoutException, Exception {
        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
                post.setEntity(entity);
            }
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());

            HttpResponse res;
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }


    /**
     * 提交form表单
     *
     * @param url
     * @param params
     * @param connTimeout
     * @param readTimeout
     * @return
     * @throws ConnectTimeoutException
     * @throws SocketTimeoutException
     * @throws Exception
     */
    public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
            SocketTimeoutException, Exception {

        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
                post.setEntity(entity);
            }

            if (headers != null && !headers.isEmpty()) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());
            HttpResponse res = null;
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null
                    && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
    }

    /**
     * 发送一个 GET 请求
     */
    public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
            throws ConnectTimeoutException,SocketTimeoutException, Exception {

        HttpClient client = null;
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            get.setConfig(customReqConf.build());

            HttpResponse res = null;

            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(get);
            }

            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            get.releaseConnection();
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 从 response 里获取 charset
     */
    @SuppressWarnings("unused")
    private static String getCharsetFromResponse(HttpResponse ressponse) {
        // Content-Type:text/html; charset=GBK
        if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
            String contentType = ressponse.getEntity().getContentType().getValue();
            if (contentType.contains("charset=")) {
                return contentType.substring(contentType.indexOf("charset=") + 8);
            }
        }
        return null;
    }

    /**
     * 创建 SSL连接
     * @return
     * @throws GeneralSecurityException
     */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl)
                        throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert)
                        throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns,
                                   String[] subjectAlts) throws SSLException {
                }
            });
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (GeneralSecurityException e) {
            throw e;
        }
    }
}
           

参考文章:

https://www.jianshu.com/p/7342b7a35ffc

https://www.jianshu.com/p/4a3c585a99f4

使用OkHttp发送POST请求

OkHttp与HttpClient