httpclient请求服务的各种方法实例
<!--话不多说,直接上代码-->
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;
}
httpclient请求服务的各种方法实例的更多相关文章
- (转)ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法
早上同事用PL/SQL连接虚拟机中的Oracle数据库,发现又报了"ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务"错误,帮其解决后,发现很多人遇到过这样的问 ...
- ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法
今天用PL/SQL连接虚拟机中的Oracle数据库,发现报了“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误,也许你也遇到过,原因如下: oracle安装成功后,一直未停止 ...
- windows7 ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法
用PL/SQL连接虚拟机中的Oracle数据库,发现又报了“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误,帮其解决后,发现很多人遇到过这样的问题,因此写着这里. 也许你没 ...
- android菜鸟学习笔记24----与服务器端交互(一)使用HttpURLConnection和HttpClient请求服务端数据
主要是基于HTTP协议与服务端进行交互. 涉及到的类和接口有:URL.HttpURLConnection.HttpClient等 URL: 使用一个String类型的url构造一个URL对象,如: U ...
- oracle中监听程序当前无法识别连接描述符中请求服务 的解决方法
早上同事用PL/SQL连接虚拟机中的Oracle数据库,发现又报了“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误,帮其解决后,发现很多人遇到过这样的问题,因此写着这里. ...
- httpclient调用webservice接口的方法实例
这几天在写webservice接口,其他的调用方式要生成客户端代码,比较麻烦,不够灵活,今天学习了一下httpclient调用ws的方式,感觉很实用,话不多说,上代码 http://testhcm.y ...
- .NET Core 2.0 httpclient 请求卡顿解决方法
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip,UseProxy ...
- [oracle] ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法
ORACLE 32位数据库正常安装,sqlplus 正常连接数据库但是PL/SQL developer 64位却报出这个错误. 第一反应是缺少32位客户端.下载安装,配置完成后如图所示: 还是报这个错 ...
- 【教程】【FLEX】#002 请求服务端数据(UrlLoader)
为什么Flex需要请求服务端读取数据,而不是自己读取? Flex 是一门界面语言,主要是做界面展示的,它能实现很多绚丽的效果,这个是传统Web项目部能比的. 但是它对数据库和文件的读写 没有良好的支持 ...
随机推荐
- Java 中的 HttpServletRequest 和 HttpServletResponse 对象
HttpServletRequest对象详解 javax.servlet.http.HttpServletRequest是SUN制定的Servlet规范,是一个接口.表示请求,“HTTP请求协议”的完 ...
- 第二十八节:Java基础-进阶继承,抽象类,接口
前言 Java基础-进阶继承,抽象类,接口 进阶继承 class Stu { int age = 1; } class Stuo extends Stu { int agee = 2; } class ...
- 机器学习(Machine Learning)算法总结-决策树
一.机器学习基本概念总结 分类(classification):目标标记为类别型的数据(离散型数据)回归(regression):目标标记为连续型数据 有监督学习(supervised learnin ...
- Jenkins 集成Sonar代码质量扫描
Jenkins上安装插件 在jenkins插件安装界面安装: 插件名 SonarQube Scanner for Jenkins Jenkins上配置 jenkins中操作:系统管理-系统设置,找到 ...
- IDEA内置git功能的使用教程
IDEA内置git功能的使用教程 IDEA git IDEA被公认为是最好的java开发工具,除了在代码助手.代码提示.重构工具等方面有比较好的支持,还在各类版本控制工具(git.tfs.svn.g ...
- php几种常见排序算法
<?php //从时间上来看,快速排序和归并排序在时间上比较有优势,//但是也比不上sort排序,归并排序比较占用内存! $arr = [4,6,1,2,3,89,56,34,56,23,65] ...
- C# 动态生成类 枚举等
private void GenerateCode() { /*注意,先导入下面的命名空间 using System.CodeDom using System.CodeDom.Compiler; us ...
- 全网最详细的实用的搜索工具Listary和Everything对比的区别【堪称比Everything要好】(图文详解)
不多说,直接上干货! 引言 无论是工作还是科研,我们都希望工作既快又好,然而大多数时候却迷失在繁杂的重复劳动中,久久无法摆脱繁杂的事情. 你是不是曾有这样一种想法:如果我有哆啦A梦的口袋,只要拿出 ...
- 单区域OSPF路由协议实现网络区域互通
1.什么是OSPF协议? OSPF协议的全程是开放式最短路径优先协议,协议采用链路状态协议算法(LS协议) 2.OSPF vs RIP RIP路由协议是距离矢量路由选择协议,收敛速度慢,如果在一些大型 ...
- Hadoop项目开发笔录
1.概要 我打算分享一下,我开发Hadoop的一些心得,对于即将步入Hadoop行业的童鞋,希望我整理的这些博文对您有帮助,我打算分为以下几部分来描述. 2.步骤 注:点击链接可直接跳到指定位置 Ha ...