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项目部能比的. 但是它对数据库和文件的读写 没有良好的支持 ...
随机推荐
- swiper,一个页面使用多个轮播
代码示例: <html> <head> <link href="https://cdn.bootcss.com/Swiper/4.3.0/css/swiper. ...
- 【repost】H5的新特性及部分API详解
h5新特性总览 移除的元素 纯表现的元素: basefont.big.center.font等 对可用性产生负面影响的元素: frame.frameset.noframes 新增的API 语义: 能够 ...
- FPGA的发展史及FPGA 的基础架构
通过了解早期FPGA的发展,理解FPGA究竟是干什么的,FPGA到底在电子设计领域起到了什么样的作用,下面是一张早期的设计过程 早期的设计流程过程中,只有当硬件完成了才能够得到功能的验证,随着集成电路 ...
- 技术文档生成工具:appledoc
做项目一般都会要求写技术文档,特别是提供SDK或者基础组件的.如果手写这类技术文档的话,工作量比编写代码也少不了多少.比如 Java 语言本身就自带 javadoc 命令,可以从源码中抽取文档.本篇我 ...
- WPF 依赖属性&附加属性
依赖属性 暂无 附加属性 1.在没有控件源码的前提下增加控件的属性 2.多个控件需要用到同一种属性 使用附加属性可以减少代码量,不必为每一个控件都增加依赖属性 3.属性不确定是否需要使用 在某些上下文 ...
- Spring boot 使用 configuration 获取的属性为 null
1. 未设置 getter(),setter()方法,导致属性值注入失败: 2. spring 未扫描到该组件,在其他类中注入该对象失败,可在配置类添加 @configuration 或者 @comp ...
- python中实现排序list
作为一个非常实用的一种数据结构,排序链表用在很多方面,下面是它的python代码实现: from Node import * class OrderedList: def __init__(self) ...
- iOS-AFN Post JSON格式数据
- (void)postRequest{ AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // >>> ...
- SpringBoot初探(上传文件)
学了Spring,SpringMVC,Mybatis这一套再来看SpringBoot,心里只有一句握草,好方便 这里对今天做的东西做个总结,然后在这之间先安利一个热部署的工具,叫spring-DevT ...
- [EXP]Joomla! Component Easy Shop 1.2.3 - Local File Inclusion
# Exploit Title: Joomla! Component Easy Shop - Local File Inclusion # Dork: N/A # Date: -- # Exploit ...