1. 了解:
    在发送请求头时:
    (1)Content-Type: 发送端(客户端、服务端)发送的实体数据类型
    (2)Accept : 客户端想要接收的数据类型
    (3)Content-Type:application/x-www-form-urlencoded:指的是key=value&key=value ,get和post方式都是这个类型,只是get多了个?,post方式把参数放在请求体内
    (4)Accept中经常能看到 image/gif 等等 ,其中 / ,表示接受所有类型
    (5)请求头中存在 Connect:Keep-Alive 实际上它是一种TCP复用,每次http请求都需要tcp三次握手,浪费资源和时间,因此我们可以保持tcp通道连接一段时间,这样一次tcp连接就可以维持几次http请求。
    (6)请求头中的User-Agent: 大体指支持的浏览器,所有浏览器都想伪装成mozilla,避免代码被阉割,部分功能无法实现
    (7)具体参考:http请求参数详情
  2. 使用spring3.0提供的HTTP 请求工具RestTemplate进行接口的调用:
package xiamen.yyr.interfacecall.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:  调用接口
 * @Author:
 * @Date:2021/5/13
 */
public class HttpUtil {
    public static final String HTTPGETMETHOD = "GET";
    public static final String HTTPPOSTMETHOD = "POST";

    /*****************************x-www-form-urlencoded*******************************/

    //MultiValueMap  HttpEntity中的参数就是这个,表示一个键对应多个值,value是一个list集合
    public static <T> T postRequestByUrlencoded(String url , MultiValueMap<String , String> params , Class<T> clazz) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.exchange(url , HttpMethod.POST , httpEntity , String.class);
        if (response!=null && response.getStatusCode()==HttpStatus.OK){
            String body = response.getBody();
            if (body != null){
                Gson gson = new GsonBuilder().create();
                return gson.fromJson(body , clazz);
            }
            return  null;
        }
        return null;
    }


    public static <T> T getRequestByUrlencoded(String url , HashMap<String , Object> params , Class<T> clazz){
        RestTemplate restTemplate = new RestTemplate();

        //params 请求参数拼接
        if (params!=null && params.size()>0){
                StringBuilder urlbuilder = new StringBuilder(url);
            urlbuilder.append("?");
            for (Map.Entry<String , Object> param : params.entrySet()){
                urlbuilder.append(param.getKey()).append("=").append(param.getValue()).append("&");
            }
            url = urlbuilder.substring(0 , urlbuilder.length() - 1);
        }

        String result = restTemplate.getForObject(url , String.class);

        if (result != null){
            Gson gson = new GsonBuilder().create();
            return gson.fromJson(result , clazz);
        }
        return null;
    }


    /*****************************json*******************************/

    public static <T> T postRequestByJson(String url , String jsonObject , Class<T> clazz) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> httpEntity = new HttpEntity<>(jsonObject, headers);
        ResponseEntity<String> response = restTemplate.exchange(url , HttpMethod.POST , httpEntity , String.class);
        if (response!=null && response.getStatusCode()==HttpStatus.OK){
            String body = response.getBody();
            if (body != null){
                Gson gson = new GsonBuilder().create();
                return gson.fromJson(body , clazz);
            }
            return  null;
        }
        return null;
    }
}

3.使用java.net自带的HttpURLConnection进行第三方接口的调用:

package xiamen.yyr.interfacecall.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author:
 * @Date:2021/5/17
 */
public class HttpUtil2 {

    /****************************************x-www-form-urlencoded*********************************************/
    public static <T> T getRequestByUrlencoded(String path , HashMap<String , Object> params, Type clazz){
        HttpURLConnection conn = null;
        BufferedReader br = null;
        InputStream is = null;
        String body = "";
        StringBuffer sb = new StringBuffer(path);
        //请求参数拼接到路径上
        if (!CollectionUtils.isEmpty(params)){
            sb.append("?");
            for (Map.Entry<String , Object> entry : params.entrySet()){
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            body = sb.substring(0 , sb.length()-1);
        }
        try {
            URL url = new URL(body);
            //打开与url之间的连接
            conn = (HttpURLConnection) url.openConnection();
            //不设置默认使用get
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept" , "*/*");
            conn.setRequestProperty("user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("content-Type" , "application/x-www-form-urlencoded");
            conn.setRequestProperty("connection" , "keep-Alive");

            //本次连接是否自动使用重定向
            conn.setInstanceFollowRedirects(true);
            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            StringBuffer result = new StringBuffer();
            while ((body=br.readLine()) != null){
                result.append(body);
            }
            body = result.toString();
            if (Strings.isNotBlank(body)){
                Gson gson = new GsonBuilder().create();
                return gson.fromJson(body , clazz);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null){
                conn.disconnect();
            }
        }
        return null;
    }


    public static <T> T postRequestByUrlencoded(String path , HashMap<String , String> headers , Type clazz){
        DataOutputStream out = null;
        BufferedReader br = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        StringBuffer sb = new StringBuffer();
        StringBuffer result = new StringBuffer();
        String body = "";
        try {
            URL url = new URL(path);
            //打开与url之间的连接
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式
            conn.setRequestMethod("POST");
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            //设置本次连接是否自动重定向
            conn.setInstanceFollowRedirects(true);
            //设置通用的请求属性
            conn.setRequestProperty("accept" , "*/*");
            conn.setRequestProperty("connection" , "keep-Alive");
            conn.setRequestProperty("user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("content-Type" , "application/x-www-form-urlencoded");

            if (!CollectionUtils.isEmpty(headers)){
                for (Map.Entry<String , String> entry : headers.entrySet()){
                    sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                body =  sb.substring(0 , sb.length()-1);
            }

            //setDoOutput设置是否向httpUrlConnection输出,setDoInput设置是否向httpUrlConnection读入,发送post请求必须设置这两个属性
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //获取URLConnection对象对应的输出流
            out = new DataOutputStream(conn.getOutputStream());
            //发送请求参数即数据
            out.writeBytes(body);
            out.flush();
            //获取URLConnection对象对应的输入流
            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str=br.readLine())!=null){
                result.append(str);
            }
            str = result.toString();
            if (Strings.isNotBlank(str)){
                Gson gson = new GsonBuilder().create();
                return gson.fromJson(str , clazz);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                conn.disconnect();
            }
        }
        return null;
    }

/*************************************application/json*************************************************/
   //此方法可以使用,但具体是否正确有待商榷
   //首先:get请求方式传递json数据应该放在请求协议包的哪里,其次:setDoOutput方法要设置为true,即使是get方式,否则无法向URLConnection发送数据
    public static <T> T getRequestByJson(String path , String data ,Type clazz){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        StringBuffer sb = new StringBuffer();
        String result = "";

        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            conn.setRequestProperty("accept" , "*/*");
            conn.setRequestProperty("connection" , "keep-Alive");
            conn.setRequestProperty("user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("content-Type" , "application/json;charset=utf-8");
            
            //从源码看,应该是检查是否连接,未连接的话进行连接
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new OutputStreamWriter(conn.getOutputStream() , "UTF-8");
            out.write(data);
            out.flush();

            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            String body = "";
            while ((body=br.readLine())!=null){
                sb.append(body);
            }
            result = sb.toString();
            if (Strings.isNotBlank(result)){
                Gson gson = new GsonBuilder().create();
                return gson.fromJson(result , clazz);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                conn.disconnect();
            }
        }
        return null;
    }



    public static <T> T postRequestByJson(String path , String data , Type clazz){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        StringBuffer sb = new StringBuffer();
        String result = "";
        try {
            URL url = new URL(path);
            //打开与url之间的连接
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式
            conn.setRequestMethod("POST");
            //设置通用的请求属性
            conn.setRequestProperty("accept" , "*/*");
            conn.setRequestProperty("connection" , "keep-Alive");
            conn.setRequestProperty("user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("content-Type" , "application/json;charset=utf-8");

            //setDoOutput设置是否向httpUrlConnection输出,setDoInput设置是否向httpUrlConnection读入,发送post请求必须设置这两个属性
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream() , "UTF-8");
            //发送请求参数即数据
            out.write(data);
            out.flush();

            //获取URLConnection对象对应的输入流
            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str=br.readLine())!=null){
                sb.append(str);
            }
            str = sb.toString();
            if (Strings.isNotBlank(str)){
               Gson gson = new GsonBuilder().create();
               return gson.fromJson(sb.toString() , clazz);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                conn.disconnect();
            }
        }
        return null;
    }
}

  1. java11使用了HttpClient调用第三方接口:相比HttpURLConnection,其方法更简便,并且支持发送异步请求(具体参考疯狂java讲义P836)
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐