java使用http代理访问服务器

1. HttpClient使用代理调用

依赖

      <!--    发送multipart/form-data类型, MultipartEntityBuilder类需要这个依赖-->
      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpmime</artifactId>
          <version>4.5</version>
      </dependency>
      
      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.8</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
      <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpcore</artifactId>
          <version>4.4.11</version>
      </dependency>

上工具类,亲测有效

创建代理地址(公共方法、所有代理引用)

public static  HttpHost addProxy(){
		//代理地址、端口号、协议
		return new HttpHost("9.236.225.252", 8080, "http");  //添加代理
	}

 

①:get请求(url上带参数)

在这里插入图片描述


	public static String doGet(String url, Map<String, String> param) {

		// 创建代理地址
		HttpHost proxy = addProxy();
		
		//账号密码 =="ap1","adpd65"
		BasicCredentialsProvider provider = new BasicCredentialsProvider();
		provider.setCredentials(new AuthScope(proxy),new UsernamePasswordCredentials("ap1","adpd65"));
		//设置账号密码
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			//设置代理配置
			RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
			httpGet.setConfig(config);

			// 执行请求
			response = httpclient.execute(httpGet);
			logger.info("代理返回结果======"+response);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
			logger.info("华为云ocr返回结果" + resultString);
		} catch (Exception e) {
			logger.error("总公司华为云ocr接口异常" + e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

②:post请求(请求头带token,请求体为urlencode)

在这里插入图片描述

public static String doPost(String url, Map<String, String> param, String token) {

		logger.info("开始进行识别");
		logger.info("--url:{},---para:{},---token:{}"+url+param+token);
		
		//添加代理
		HttpHost proxy = addProxy();
		//账号密码
		BasicCredentialsProvider provider = new BasicCredentialsProvider();
		provider.setCredentials(new AuthScope(proxy),new UsernamePasswordCredentials("app1","adpp#1d65"));
		//设置账号密码
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();

		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			if (!StringUtils.isEmpty(token)) {
				httpPost.setHeader("Authorization", token);
			}
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); //设置代理配置
			httpPost.setConfig(config);
			// 执行http请求
			response = httpClient.execute(httpPost);
			logger.info("代理返回结果======"+response);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
			logger.info("返回结果" + resultString);

		} catch (Exception e) {
			logger.error("接口异常" + e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}

②:post请求(请求体为json数据)

在这里插入图片描述
在这里插入图片描述

//发送json数据
	public static String doPostJson(String url, String json) {
		//创建代理
		HttpHost proxy = addProxy();
		
		// 创建带有账号密码的Httpclient对象
		BasicCredentialsProvider provider = new BasicCredentialsProvider();
		provider.setCredentials(new AuthScope(proxy),new UsernamePasswordCredentials("app1","adpp#1d65"));
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
		
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			
			//设置代理配置
			RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); 
			httpPost.setConfig(config);
			
			// 执行http请求
			response = httpClient.execute(httpPost);
			logger.info("代理返回结果======"+response);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}

以上三种代理方法,可以自由变更为自己需要的业务场景

 

2. HttpClient不使用代理调用

 

①:post请求(发送json数据)

    //发送json数据
    public static String doPostJson(String url, String json) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);

            response = httpClient.execute(httpPost);
            log.info("代理返回结果======" + response);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            return resultString;
        } catch (Exception e) {
            log.info("代理执行http请求失败============");
            throw new CustomerException("代理执行http请求失败============");
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

 

②:post请求(multipart/form-data类型,文件+数据)

在这里插入图片描述
在这里插入图片描述

    /**
     * 发送 multipart/form-data  post请求
     *
     * @param url       URL
     * @param jsonParam 携带的参数
     * @param file      文件( 文件类型:MultipartFile )
     * @return
     * @throws IOException
     */
    public static String httpPostWithdate(String url, String jsonParam, MultipartFile file) throws IOException {


//        System.out.println(jsonParam);
        HttpPost httpPost = new HttpPost(url);
//      随机设计
        String boundary = "--------------4585696313564699";
        //设置请求头(百度好多都没有设置这个请求头)
        httpPost.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        //模拟浏览器
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //字符编码
        builder.setCharset(Charset.forName("UTF-8"));
        builder.setBoundary(boundary);
        //设置请求携带的参数 (传入的jsonParam),这里为了示例,直接写死
        builder.addTextBody("partnerCode", "P1624869230466", ContentType.create("text/plain", Charset.forName("UTF-8")));
        builder.addTextBody("partnerSecret", "e0641793f356c85c", ContentType.create("text/plain", Charset.forName("UTF-8")));
        builder.addTextBody("svcCode", "I1618304104686", ContentType.create("text/plain", Charset.forName("UTF-8")));
        builder.addTextBody("requestId", "46954598", ContentType.create("text/plain", Charset.forName("UTF-8")));
        builder.addTextBody("businessNo", "8615012021110112000093", ContentType.create("text/plain", Charset.forName("UTF-8")));
        builder.addTextBody("timestamp", "20210628152503", ContentType.create("text/plain", Charset.forName("UTF-8")));
        builder.addTextBody("sign", "NbEhUuFpHUyb3NO3iC8cZQ==", ContentType.create("text/plain", Charset.forName("UTF-8")));
        //这里根据自身业务需求,自行判断
        if (file != null) {
            //设置请求携带的文件(文件类型:MultipartFile )
            //file.getName()  会返回不正确的结果  不知是不是接口还是java的原因
            builder.addBinaryBody(
                    "file",
                    file.getInputStream(),
                    ContentType.MULTIPART_FORM_DATA,
                    file.getOriginalFilename()
            );
        }
//        file 文件这样写
//        builder.addPart("参数名",new FileBody(file));
        HttpEntity multipart = builder.build();
        HttpResponse resp = null;
        try {
            httpPost.setEntity(multipart);
            // 提交
            resp = client.execute(httpPost);
            //根据业务需求 自行调整
            HttpEntity entity = resp.getEntity();
            respContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
        }
        return respContent;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值