java使用httpclient访问连接

package com.base.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

public class HttpUtil {

    /**
     * post请求
     * @param urlStr
     * @param param
     * @param userAgent
     * @return
     */
    public static String httpPost(String urlStr,String param,String userAgent){
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(60 * 1000);
            if(StringUtils.isNotBlank(userAgent)){
                conn.setRequestProperty("User-Agent",
                        userAgent);
            }
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            BufferedOutputStream out = new BufferedOutputStream(conn
                    .getOutputStream());
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            bw.write(param);
            bw.flush();
            bw.close();

            if (conn.getResponseCode()==200){
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String tempStr = null;
                String str = "";
                while ((tempStr=br.readLine())!=null){
                    str +=tempStr;
                }
                System.out.println("返回结果===="+str);
                br.close();
                return str;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * post请求
     * @param urlStr
     * @param xmlParam
     * @return
     */
    public static String httpPost(String urlStr,String xmlParam){
        return httpPost(urlStr,xmlParam,null);
    }


    /**
     * 调用外部接口,并返回响应结果
     * @param httpUrl
     * @param params
     * @return
     * @throws Exception
     */
    public static String sendHttpPostRequest(String httpUrl, Map<String, String> params) throws Exception{

        URL url = new URL(httpUrl);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        if(params != null && params.size() > 0){
            StringBuilder sb = new StringBuilder();
            for(Map.Entry<String, String> entry : params.entrySet()){
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            conn.getOutputStream().write(sb.substring(1).getBytes("utf-8"));
        }
        conn.connect();
        String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));

        conn.disconnect();
        return responseContent;
    }

    public static String sendHttpGetRequest(String httpUrl, Map<String, String> params) throws Exception{

        try {
            if(params != null && params.size() > 0){
                StringBuilder sb = new StringBuilder();
                for(Map.Entry<String, String> entry : params.entrySet()){
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
                sb = new StringBuilder(sb.substring(1));
                if(httpUrl.contains("?")){
                    httpUrl += "&"+sb.toString();
                }else{
                    httpUrl += "?"+sb.toString();
                }
            }
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.connect();
            String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
            conn.disconnect();
            return responseContent;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    //获得网络路径
    public static InputStream getImageStream(String url) throws Exception{
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return connection.getInputStream();
        }else{
            throw new Exception("响应状态:" + connection.getResponseCode() + "\n" +
                    "响应内容:" + connection.getResponseMessage());
        }
    }

    //判断当前请求是否有效
    public static boolean sendGetRequestAck(String url) throws Exception{
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return true;
        }else{
            return false;
        }
    }

    //把字节流转换成字节数组
    public static byte[] toByteArray(InputStream input) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*4];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //把字节数组转换成字节流
    public static InputStream toInputStream(byte[] bytes){
        return new ByteArrayInputStream(bytes);
    }

    //字节流转换字节流
    public static InputStream toInputStream(InputStream input){
        return toInputStream(toByteArray(input));
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值