<!--话不多说,直接上代码-->

import com.csis.ConfigManager
import com.csis.io.web.DefaultConfigItem
import net.sf.json.JSONObject
import org.apache.commons.lang.StringUtils
import org.apache.http.*
import org.apache.http.client.ClientProtocolException
import org.apache.http.client.HttpClient
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.entity.UrlEncodedFormEntity
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.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.entity.StringEntity
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import java.security.cert.CertificateException
import java.security.cert.X509Certificate

/**
* HTTP GET方法
* @param urlWithParams url和参数
* @return 返回字符串UTF-8
* @throws Exception
*/
public static String httpGet(String urlWithParams) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(urlWithParams);
CloseableHttpResponse response = null;
String resultStr = null;
try {
//配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(50)
.setConnectTimeout(50)
.setSocketTimeout(60000).build();
httpget.setConfig(requestConfig);

response = httpclient.execute(httpget);
logger.debug("StatusCode -> " + response.getStatusLine().getStatusCode());
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
if (entity) resultStr = EntityUtils.toString(entity, "utf-8");
}
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
} finally {
httpget.releaseConnection();
httpclient.close();
if (response) response.close();
}
resultStr
}

/**
* HTTP POST方法
* @param url 请求路径
* @param formData 参数,map格式键值对
* @return 返回字符串UTF-8
* @throws ClientProtocolException
* @throws IOException
*/
static String httpPost(String url, Map<String, String> formData) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
String resultStr = null;
try {
if (formData) {
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formData.each { key, value ->
formParams.add(new BasicNameValuePair(key, value));
}
httppost.setEntity(new UrlEncodedFormEntity(formParams, 'utf-8'));
}
response = httpclient.execute(httppost);
logger.debug("StatusCode -> " + response.getStatusLine().getStatusCode());
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
if (entity) resultStr = EntityUtils.toString(entity, "utf-8");
}
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
} finally {
httppost.releaseConnection();
httpclient.close();
if (response) response.close();
}
resultStr
}

static String httpPostFile(String url, File file) throws ClientProtocolException, IOException {
if (file == null || !file.exists() || StringUtils.isBlank(url)) {
println("file not exists");
return null;
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
try {
// FileBody fileBody = new FileBody(file);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", file);
post.setEntity(multipartEntityBuilder.build());
response = httpclient.execute(post);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
post.releaseConnection();
httpclient.close();
response.close();
}
return null;
}

static JSONObject doPost(String url, JSONObject json) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}

static httpGetFile(String url,String path){
if(!url) return null
CloseableHttpClient httpclient
if(url.startsWith("https")){
httpclient = httpsClient() as CloseableHttpClient
}else {
httpclient = HttpClients.createDefault()
}
HttpGet httpget = new HttpGet(url)
CloseableHttpResponse response = null
try {
//配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(50)
.setConnectTimeout(50)
.setSocketTimeout(60000).build()
httpget.setConfig(requestConfig)

response = httpclient.execute(httpget)
logger.debug("StatusCode -> " + response.getStatusLine().getStatusCode())
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity()
if(entity != null) {
InputStream inputStream = entity.getContent()
File file
if(path){
file = new File(path)
if(file.isDirectory()){
file = new File("${file.path}/${System.currentTimeMillis()}")
}
}else {
String fileName = null
Header contentHeader = response.getFirstHeader("Content-Disposition")
if(contentHeader){
HeaderElement[] values = contentHeader.getElements()
if(values){
NameValuePair param = values[0].getParameterByName("filename")
if(param){
fileName = param.value
}
}
}

if(!fileName){
fileName = "${System.currentTimeMillis()}"
}

file = new File("${ConfigManager.instance.get(DefaultConfigItem.IO_UPLOAD_PATH)}/${fileName}")
}

FileOutputStream fos = new FileOutputStream(file)
byte[] buffer = new byte[4096]
int len
while((len = inputStream.read(buffer) )!= -1){
fos.write(buffer, 0, len)
}
fos.close()
inputStream.close()

return file.absolutePath
}
}
} catch (Exception ex) {
ex.printStackTrace()
} finally {
httpget.releaseConnection()
httpclient.close()
if (response) response.close()
}

null
}

private static HttpClient httpsClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS")
X509TrustManager tm = new X509TrustManager() {
X509Certificate[] getAcceptedIssuers() {
return null
}

void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}

void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
}
ctx.init(null, [tm] as TrustManager[], null)
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
ctx, NoopHostnameVerifier.INSTANCE)
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(ssf).build()
return httpclient
} catch (Exception e) {
return HttpClients.createDefault()
}
}

public static String dealCons(String param, String input, String url) {
String output = "";
try {
String reqUrl = url;
URL restServiceURL = new URL(reqUrl);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL
.openConnection();
// param 输入小写,转换成 GET POST DELETE PUT
httpConnection.setRequestMethod(param.toUpperCase());
if ("post".equals(param)) {
// 打开输出开关
httpConnection.setDoOutput(true);
// 传递参数
// String input = "&jsonStr="+URLEncoder.encode(jsonStr, "UTF-8");
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
}
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException(
"HTTP GET Request Failed with Error code : "+httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(
new InputStreamReader((httpConnection.getInputStream())));
// 结果集
output = responseBuffer.readLine();
println(httpConnection.getResponseCode()+"====================="+output);
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}

转载于:https://www.cnblogs.com/panca/p/10682009.html

httpclient请求服务的各种方法实例相关推荐

  1. java连接数据库12514_ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法...

    早上同事用PL/SQL连接虚拟机中的Oracle数据库,发现又报了"ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务"错误,帮其解决后,发现很多人遇到过这样的问 ...

  2. windows7 ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法

    windows7 ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法 参考文章: (1)windows7 ORA-12514 TNS 监听程序当前无法识别连接描述符中请求 ...

  3. win10提示系统资源不足,无法完成请求服务的解决方法

    win10提示系统资源不足,无法完成请求服务的解决方法 win10提示系统资源不足,无法完成请求服务的解决方法 问题描述 分析: 操作: 验证: 举一反三: 问题描述 最近安装xmlspy2013 破 ...

  4. 安装EA后win10提示系统资源不足,无法完成请求服务的解决方法

    win10提示系统资源不足,无法完成请求服务的解决方法 安装enterprise architect 14 原因 解决方法 安装enterprise architect 14 教程https://bl ...

  5. oracle中监听程序当前无法识别连接描述符中请求服务 的解决方法

    早上同事用PL/SQL连接虚拟机中的Oracle数据库,发现又报了"ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务"错误,帮其解决后,发现很多人遇到过这样的问 ...

  6. ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法

    51CTO在线视频课程,欢迎大家访问试听 <测试系列课程之缺陷管理概述> http://edu.51cto.com/course/course_id-447.html <软件测试基础 ...

  7. win10win7打开软件提示系统资源不足,无法完成请求服务的解决方法

    有些win7.win10用户莫名的遇到了一个问题,就是安装部分软件的时候提示系统资源不足,无法完成请求服务,刚开始以为是系统缺少了某些组件,结果发现是国外杀毒迈克菲(McAfee)在捣鬼. 报错 关闭 ...

  8. IP:PORT failed to respond HttpClient 请求服务端报错

    此问题排查方向为连接本身的问题 比如:客户端使用连接池技术访问服务端,连接池默认情况下使用了长连接来避免每次建立连接消耗,从而提升性能,但是服务端设置了keepalive timeout ,服务端在规 ...

  9. 【请求后台接口】30秒完成Angular10精简版HttpClient请求服务搭建

    ng g s services/http app.module.ts ... @NgModule({declarations: [...],imports: [...HttpClientModule, ...

  10. 启动mysql55命令_mysql服务的启动和停止登陆mysql增加新用命令和方法实例教程

    mysql服务的启动和停止登陆mysql增加新用命令和方法实例教程,mysql常见常用操作命令汇总总结,增删查改命令,启动用户管理,数据库管理等. mysql服务的启动和停止 net stop mys ...

最新文章

  1. cocos2d游戏jsc文件格式解密,SpideMonkey大冒险
  2. linux 支持的字体命令,Linux设置显示中文和字体
  3. ADAMoracle预言机的发展趋势和特点
  4. 11.2.2 jQuery选择器
  5. wamp增加php,新版PHPWAMP自定义添加PHP版本方法步骤
  6. HALCON示例程序fin.hdev通过形态学检测缺陷
  7. ORA-00376: file X cannot be read at this time 问题解决
  8. [tools]python的mkdocs模块分分钟将md搞成一个网站
  9. 一个优雅地探索相关性的新可视化方法
  10. Java集合里的一些“坑”
  11. Windows中绕过更新直接关机
  12. css radio 垂直居中显示,CSS表单元素垂直居中完美解决方案
  13. JPG、PNG和GIF图片的基本原理及优化方法
  14. linux扩充home目录,扩大/home目录的空间(转)
  15. 大宗商品交易挂接银行的几个问题?
  16. kubernetes Auditing 实战
  17. Bagging 和 Boosting理解、区别与联系
  18. 二维数组的几种定义方法
  19. PHP解析错误 PHP Parse error: syntax error, unexpected '[' in
  20. 快速入门mybatis(查询、添加日志、插入)

热门文章

  1. jumpserver的安装
  2. Kotlin中正则表达式分析
  3. Apache - 403错误
  4. Python自带函数map(),zip()等
  5. 批量获取客户端时间偏差
  6. 可展开的UITableViewCell
  7. [Yii Framework] Another method to run cron in the share space server.
  8. Sniffer安全技术从入门到精通
  9. 和方舟rust一样的手游_2020年最令人期待的端改手游盘点,《方舟:生存进化》名列前茅...
  10. java redirect 超时_java – Spring Security 3.0重定向到超时的页面