Http请求设置代理&Java用curl命令发起请求小结(自用)

1、CloseableHttpClient设置代理发起get/post请求如下:

package cn.yiducloud.hospitaladmin.entryexit.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author hao.feng
 * @date 2019/05/25 1:35
 */
@Slf4j
public class CloseableHttpClientUtil {


    /**
     * 以get方式调用第三方接口
     * @param url
     * @param token
     * @return
     */
    public static String doGet(String url, String token) {
        HttpGet httpGet = new HttpGet(url);
//        HttpGet httpGet = new HttpGet("http://103.4.188.131:8080/bruhealth/service/get_records?source=etp&startEntryDate=2021-7-26&endEntryDate=2021-7-26");
        CloseableHttpClient client = setGetProxy(httpGet, "172.18.220.40", 80);
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36");
        httpGet.addHeader("Authorization", "Bearer " + token);
        CloseableHttpResponse response= null;
        try {
            response = client.execute(httpGet);
            // 获取返回实体
            if (response != null){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    String resp = EntityUtils.toString(entity, "utf-8");
                    return resp;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //关闭httpClient
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "failed";
    }

    /**
     * 以post方式调用第三方接口
     * @param url
     * @return
     */
    public static String doPost(String url) {
//        HttpPost httpPost = new HttpPost(url);
        HttpPost httpPost = new HttpPost("http://103.4.188.131:8080/bruhealth/service/get_token");
        CloseableHttpClient client = setPostProxy(httpPost, "172.18.220.40", 80);
        httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36");
        CloseableHttpResponse response= null;
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("grant_type", "client_credentials");
            jsonObject.put("client_id", "bruhealth");
            StringEntity se = new StringEntity(jsonObject.toString());
            se.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            //设置请求参数
            httpPost.setEntity(se);
            response = client.execute(httpPost);
            // 获取返回实体
            if (response != null){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    String resp = EntityUtils.toString(entity, "utf-8");
                    return resp;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //关闭httpClient
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "failed";
    }
    /**
     * 设置代理
     * @param httpGet
     * @param proxyIp
     * @param proxyPort
     * @return
     */
    public static CloseableHttpClient setGetProxy(HttpGet httpGet, String proxyIp, int proxyPort){
        // 创建httpClient实例
        CloseableHttpClient httpClient= HttpClients.createDefault();
        //设置代理IP、端口
        HttpHost proxy=new HttpHost(proxyIp,proxyPort,"http");
        //也可以设置超时时间   RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(3000).setSocketTimeout(3000).setConnectionRequestTimeout(3000).build();
        RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);
        return httpClient;
    }
    /**
     * 设置代理
     * @param httpPost
     * @param proxyIp
     * @param proxyPort
     * @return
     */
    public static CloseableHttpClient setPostProxy(HttpPost httpPost,String proxyIp,int proxyPort){
        // 创建httpClient实例
        CloseableHttpClient httpClient= HttpClients.createDefault();
        //设置代理IP、端口
        HttpHost proxy=new HttpHost(proxyIp,proxyPort,"http");
        //也可以设置超时时间   RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(3000).setSocketTimeout(3000).setConnectionRequestTimeout(3000).build();
        RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
        httpPost.setConfig(requestConfig);
        return httpClient;
    }
}

2、Java发起curl请求示例:

package cn.yiducloud.hospitaladmin.entryexit.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author: hao.feng@yiducloud.cn
 * @Description: 执行curl命令的工具类
 * @Date: 2021-07-22 17:16:45
 **/
public class CurlUtil {

    /**
     * 命令需要以数组的形式传递参数,就是把正常的命令以空格切分成数组就行了。而且参数前后不能有空格,不然会报错
     * @param cmds 例如:{"curl", "-x", "172.18.220.40:80",
     *             "--location", "--request", "POST",
     *             "http://103.4.188.131:8080/bruhealth/service/get_token",
     *             "--data-urlencode", "grant_type=client_credentials",
     *             "--data-urlencode", "client_id=bruhealth"};//必须分开写,不能有空格
     * @return
     */
    public static String execCurl(String[] cmds){
        ProcessBuilder process = new ProcessBuilder(cmds);
        process.redirectErrorStream(true);
        Process p;
        try {
            p = process.start();
            BufferedReader reader  = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();

        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        return null;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值