HttpURLConnection访问第三方接口

请求第三方提供的接口,可以通过HttpURLConnection发送HTTP请求

引入所需要的jar包

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
                <groupId>org.web3j</groupId>
            <artifactId>core</artifactId>
            <version>5.0.0</version>
        </dependency>

1.通过HttpURLConnection发送GET请求

1.1无参的GET请求

public static String getGeneralUrl(String url,String contentType,String encoding) throws Exception{
        URL url1 = new URL(url);
        HttpURLConnection conn=(HttpURLConnection)url1.openConnection();

        conn.setReadTimeout(5000);//设置超时时间
        conn.setRequestMethod("GET");//设置请求类型

        //设置请求头
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Connection", "keep-alive");// 维持长连接
        conn.setUseCaches(false);//不允许缓存
        //连接
        conn.connect();

         //打印请求头信息

        Map<String, List<String>> header = conn.getHeaderFields();
        for (String key : header.keySet()) {
            System.out.println(key+"--->"+header.get(key));
        }

         //获取响应信息
        BufferedReader in = new BufferedReader(new         InputStreamReader(conn.getInputStream(),encoding));
        String result = "";
        String line;
        while((line=in.readLine())!=null){
            result += line;
        }
        in.close();
        return result;
    }

1.2有参的GET请求

        参数拼接到URL后面

public static String getGeneralUrl(String url,String contentType,Map<String, Object> params,String encoding) throws Exception{
        if(params!=null && !params.isEmpty()){
            String p = "?";
            Set<Entry<String, Object>> entrySet = params.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                if(entry!=null&&entry.getKey()!=null){
                    p += entry.getKey()+"="+entry.getValue()+"&";
                }
            }
            p = p.substring(0, p.length()-1);
            url += p; 
        }

        System.out.println("**URL**"+url);
        URL url1 = new URL(url);
        HttpURLConnection conn=(HttpURLConnection)url1.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setUseCaches(false);
        
        conn.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),encoding));
        String result = "";
        String line;
        while((line=in.readLine())!=null){
            result += line;
        }
        in.close();
        return result;
    }

2.通过HttpURLConnection发送POST请求

注意:

        1.请求参数如果是普通的,需要拼接到url后面;

        2.请求参数在RequestBody里,需要写入到流里面

        3.params是JSON字符串,可以用Gson类处理

    public static String postGeneralUrl(String url,String contentType,Map<String, Object> paramsMap,String params,String encoding,String token) throws Exception{

    if(paramsMap!=null && !paramsMap.isEmpty()){
            String p = "?";
            Set<Entry<String, Object>> entrySet = paramsMap.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                if(entry!=null&&entry.getKey()!=null){
                    p += entry.getKey()+"="+entry.getValue()+"&";
                }
            }
            p = p.substring(0, p.length()-1);
            url += p; 
        }
        System.out.println("**URL**"+url);
        URL url1 = new URL(url);
        HttpURLConnection conn=(HttpURLConnection)url1.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Connection", "keep-alive");

        conn.setDoOutput(true);//需要输出
        conn.setDoInput(true);//需要输入
        conn.setUseCaches(false);
        Map<String, List<String>> header = conn.getHeaderFields();
        for (String key : header.keySet()) {
            System.out.println(key+"--->"+header.get(key));
        }

        //放在body中的参数
        if(params!=null && !"".equals(params)){
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(params.getBytes(encoding));
            out.flush();
            out.close();
        }
        conn.connect();
        String result = "";
        int resultCode=conn.getResponseCode();//获取响应状态
        if(HttpURLConnection.HTTP_OK==resultCode){
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),encoding));
            String line;
            while((line=in.readLine())!=null){
                result += line;
            }
            in.close();
        }
        return result;
    }

其他说明

1.也可以设置其他的请求方式,如“DELETE”、“PUT”

        conn.setRequestMethod("POST");

2.以下贴出Gson的工具类,实现JSON之间转换

2.1引入jar包

<dependency>
            <groupId>top.jfunc.json</groupId>
            <artifactId>Json-Gson</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk13</classifier>
        </dependency>

2.2工具类

public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();
    
    public static String toJson(Object value){
        return gson.toJson(value);
    }
    public static <T> T formJson(String json,Class<T> classOfT) throws JsonParseException{
        return gson.formJson(json,classOfT);
    }
    public static <T> T formJson(String json,Type typeOfT) throws JsonParseException{
        return gson.formJson(json,typeOfT);
    }
}

2.3使用

                Map<String,String> map = new HashMap<String, String>();
                map.put("user", "USER1");
                map.put("password", "123");
                String param = GsonUtils.toJson(map);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值