httpClient设置代理模式

package com.hisense.hiioc.share.utils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.models.auth.In;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;


@Component
public class HttpClientUtil {

    private  static  String posturl;
    private  static  String authurl;

    private static   String postaddress;

    private static   String postpassword;

    private  static  String proxyip;

    private  static  String proxyprot;

    private static  String targetport;
    @Value("${blockchain.posturl}")
    public  void setPosturl(String posturl) {
        HttpClientUtil.posturl = posturl;
    }

    @Value("${blockchain.authurl}")
    public  void setAuthurl(String authurl) {
        HttpClientUtil.authurl = authurl;
    }
    @Value("${blockchain.postaddress}")
    public  void setPostaddress(String postaddress) {
        HttpClientUtil.postaddress = postaddress;
    }

    @Value("${blockchain.postpassword}")
    public  void setPostpassword(String postpassword) {
        HttpClientUtil.postpassword = postpassword;
    }
    @Value("${blockchain.isproxymodle.proxyip}")
    public  void setProxyip(String proxyip) {
        HttpClientUtil.proxyip = proxyip;
    }

    @Value("${blockchain.isproxymodle.proxyprot}")
    public  void setProxyprot(String proxyprot) {
        HttpClientUtil.proxyprot = proxyprot;
    }
    @Value("${blockchain.isproxymodle.targetip}")
    public  void setTargetip(String targetip) {
        HttpClientUtil.targetip = targetip;
    }
    private   static String targetip;
    @Value("${blockchain.isproxymodle.targetport}")
    public  void setTargetport(String targetport) {
        HttpClientUtil.targetport = targetport;
    }

    public  String sendJsonPostHeaderforProxy(String url,String[] keys,Object[] values,String headerKey,String headerValue){
        HttpPost httpPost=null;
        CloseableHttpClient client=null;
        JSONObject jsonParam=null;
        String responseContent=null;
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
             httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type","application/json");
            httpPost.setHeader(headerKey,headerValue);
            HttpHost target = new HttpHost(targetip, Integer.parseInt(targetport),
                    "http");
            HttpHost proxy = new HttpHost(proxyip, Integer.parseInt(proxyprot), "http");
            // 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).setProxy(proxy).build();

            httpPost.setConfig(requestConfig);

            jsonParam= new JSONObject();
//            jsonParam.put("username","ZMDC");
//            jsonParam.put("sms","1440396636364");
//            jsonParam.put("sign","48cd217b452cc1df");
              if(keys.length>0&&values.length>0&&keys.length==values.length) {
                for(int i=0;i<keys.length;i++){
                    jsonParam.put(keys[i],values[i]);
                }
                String sss=jsonParam.toJSONString();
                StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");

                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                //httpPost.setHeader(headerKey,headerValue);
                // httpPost.addHeader(headerKey,headerValue);
                CloseableHttpResponse result = httpClient.execute(target,httpPost);
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    return str;
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }catch(Exception e){
            e.printStackTrace();

        }finally {
            try{
                client.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public   void  storageSend(String namevalue,String datavalue, String busTypevalue)
    {
        HttpClientUtil util=new HttpClientUtil();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("posturl==================================="+posturl);
                System.out.println("targetport==================================="+targetport);
                String headerValue=gettokenforproxy();
                String url=posturl;
                String[] keys={"name","type","data","busType"};
                String[] values={namevalue,"02",datavalue,busTypevalue};
                String headerKey="x-access-token";
                String responseTest=sendJsonPostHeaderforProxy( url, keys, values, headerKey, headerValue);
                System.out.println(responseTest);
            }

        }).start();

    }
    public    String gettokenforproxy() {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(authurl);
        HttpHost target = new HttpHost(targetip, Integer.parseInt(targetport),
                "http");
        HttpHost proxy = new HttpHost(proxyip, Integer.parseInt(proxyprot), "http");
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).setProxy(proxy).build();
        httpPost.setConfig(requestConfig);
        try {
            String paramjson= "{\n" +
                    "\"address\":\""+postaddress+"\",\n" +
                    "\"password\":\""+postpassword+"\"\n" +
                    "}";
            StringEntity entity = new StringEntity(paramjson);
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            httpPost.setEntity(entity);

            CloseableHttpResponse result = httpClient.execute(target,httpPost);
            // 请求发送成功,并得到响应
                String str = "";
                try {
                        // 读取服务器返回过来的json字符串数据
                        str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                   return str;
                } catch (Exception e) {

                }
        } catch (IOException e) {

            System.out.println(e);
        } finally {
            httpPost.releaseConnection();
        }
       return null;
    }

//测试main方法


}


//注意两点 1.类上加@Component标签,属性上加@value标签 2.set方法不是静态方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值