Java使用代理发送Post请求
2019-05-14 12:17
176 查看
/** *@param URL 需要请求的地址 **/ private String requestHttpsPost() throws Exception { String result; HttpPost post = new HttpPost(URL); CloseableHttpClient client = null; CloseableHttpResponse response = null; HttpEntity entity = null; try { post.setHeader("Accept", "application/json, text/javascript, */*; q=0.01"); post.setHeader("X-Requested-With", "XMLHttpRequest"); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); List<BasicNameValuePair> formparam = new ArrayList<>(); //表单请求参数 post.setEntity(new UrlEncodedFormEntity(formparam)); // 设置客户端超时时间 RequestConfig config = RequestConfig.custom() .setSocketTimeout(50000).setConnectTimeout(50000) .setConnectionRequestTimeout(50000).build(); HttpClientBuilder httpClientBuilder = HttpClients.custom() .setDefaultRequestConfig(config); /*** *ForeignProxyHelp为自行封装的一个代理类 */ ChannelProxy channelProxy = foreignProxyHelp.getProxy(); if (channelProxy != null) { logger.info(channelProxy.getStunnelHost() + "---------------"); //取代理服务器的ip和端口 HttpHost targetHost = new HttpHost( channelProxy.getStunnelHost(), Integer.valueOf(channelProxy.getStunnelPort())); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(channelProxy.getProxyAccounts(), channelProxy.getPassword())); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setProxy(targetHost); } logger.info("设置代理完成..."); client = httpClientBuilder.build(); logger.info("获取客户端请求..."); // 执行POST请求 response = client.execute(post); entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); logger.info("执行请求结束...响应状态码:" + statusCode); result = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { if (post != null) { post.abort(); } throw e; } finally { EntityUtils.consume(entity); // 关闭连接 释放资源 if (post != null) { post.releaseConnection(); } if (response != null) { response.close(); } if (client != null) { client.close(); } } return result; }
相关文章推荐
- 使用Java发送GET、POST请求
- 使用java程序发送post请求给servlet
- java中使用scoket模拟http post请求发送图片或文件
- 使用java程序模拟页面发送http的post请求
- 使用Java原生API编写发送HTTP_POST请求的工具类
- java使用POST发送soap报文请求webservice返回500错误解析
- 使用java 访问发送http协议, 发送Get请求跟Post请求
- Java 中使用 HttpClient 发送 get、post 请求的方法
- JAVA中使用POST和GET发送请求
- 使用Java发送GET、POST请求
- 使用Java发送POST、GET请求【转】
- 使用Java原生API编写发送HTTP_POST请求的工具类
- 使用Java发送GET、POST请求
- java中使用scoket模拟http post请求发送图片或文件
- 使用Java发送GET、POST请求
- 使用Java发送GET、POST请求
- 使用Java发送POST、GET请求
- java使用httpclient发送post请求示例
- java中使用scoket模拟http post请求发送图片或文件
- 使用java代码发送HTTP Post请求