HttpURLConnection发送basic auth的post与get请求

HttpURLConnection发送basic auth的post与get请求
package com.skyable.account.system.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpURLConnectionUtil {
    @Value("${***.***.***}")
    public static String authUsername;
    @Value("${***.***.***}")
    public static String authPassword;
    /**
     * get请求
     * @param strUrl
     * @return
     */
    public static String httpURLConnectionGet(String strUrl){
        BufferedReader in = null;
        String username = authUsername;
        String password = authPassword;
        String auth = username+":"+password;
        //对其进行加密
        byte[] rel = Base64.encodeBase64(auth.getBytes());
        String res = new String(rel);
        try {
            //获取访问地址URL,注意GET请求若URL中包含中文字符的话,在高版本TOMCAT中会认为是不合法字符,可改为POST方式
            URL url = new URL(strUrl);
            //创建HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //添加请求头
//            conn.setRequestProperty("USER-TOKEN","eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyc2oiLCJ1c2VySWQiOiJyZWRpczp1c2VyOnRva2VuOjI3IiwiaWF0IjoxNjAzMzUwODcyLCJleHAiOjE2MDM5NTU2NzJ9.3KOsFrzpJbz_p5vjVzL3sGTWFm1yAKAAaDpKeg4DJDw");
            //请求方式,默认是GET
            conn.setRequestMethod("GET");
            //连接主机的超时时间(单位:毫秒)
            conn.setConnectTimeout(30000);
            //设置认证
            conn.setRequestProperty("Authorization","Basic " + res);
            //从主机读取数据的超时时间(单位:毫秒)
            conn.setReadTimeout(30000);
            //设置是否输出,默认是false
            conn.setDoOutput(false);
            //设置是否读入,默认是true
            conn.setDoInput(true);
            String result = "";
            int code = conn.getResponseCode();
            if(code == 200){
                //定义BufferedReader输入流读取响应,getInputStream()会自动建立连接,无需手动调用connect()连接
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                //关闭输入流
                in.close();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Post请求
     * @param strUrl
     * @return
     */
    public static String httpURLConnectionPost(String strUrl, Map params){
        String jsonString = JSONObject.toJSONString(params);
        PrintWriter out = null;
        BufferedReader in = null;

        String username = authUsername;
        String password = authPassword;
        String auth = username+":"+password;
        //对其进行加密
        byte[] rel = Base64.encodeBase64(auth.getBytes());
        String res = new String(rel);
        try {
            //获取访问地址URL
            URL url = new URL(strUrl);
            //创建HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求格式
            conn.setRequestProperty("Content-type", "application/json");
            //设置编码语言
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            //请求方式,默认是GET
            conn.setRequestMethod("POST");
            //连接主机的超时时间(单位:毫秒)
            conn.setConnectTimeout(30000);
            //从主机读取数据的超时时间(单位:毫秒)
            conn.setReadTimeout(30000);
            //设置认证
            conn.setRequestProperty("Authorization","Basic " + res);
            //设置是否输出,post请求参数要放在 http正文内,需设为true,默认是false
            conn.setDoOutput(true);
            //设置是否读入,默认是true
            conn.setDoInput(true);
            //获取字符输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
            //发送请求参数
            out.print(jsonString);
            //刷新输出流
            out.flush();
            //关闭输出流
            out.close();
            String result = "";
            int code = conn.getResponseCode();
            if(code == 200){
                //定义BufferedReader输入流读取响应,getInputStream()会自动建立连接,无需手动调用connect()连接
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                //关闭输入流
                in.close();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值