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

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请求服务的各种方法实例的更多相关文章

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

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

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

    今天用PL/SQL连接虚拟机中的Oracle数据库,发现报了“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误,也许你也遇到过,原因如下: oracle安装成功后,一直未停止 ...

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

    用PL/SQL连接虚拟机中的Oracle数据库,发现又报了“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误,帮其解决后,发现很多人遇到过这样的问题,因此写着这里. 也许你没 ...

  4. android菜鸟学习笔记24----与服务器端交互(一)使用HttpURLConnection和HttpClient请求服务端数据

    主要是基于HTTP协议与服务端进行交互. 涉及到的类和接口有:URL.HttpURLConnection.HttpClient等 URL: 使用一个String类型的url构造一个URL对象,如: U ...

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

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

  6. httpclient调用webservice接口的方法实例

    这几天在写webservice接口,其他的调用方式要生成客户端代码,比较麻烦,不够灵活,今天学习了一下httpclient调用ws的方式,感觉很实用,话不多说,上代码 http://testhcm.y ...

  7. .NET Core 2.0 httpclient 请求卡顿解决方法

    var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip,UseProxy ...

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

    ORACLE 32位数据库正常安装,sqlplus 正常连接数据库但是PL/SQL developer 64位却报出这个错误. 第一反应是缺少32位客户端.下载安装,配置完成后如图所示: 还是报这个错 ...

  9. 【教程】【FLEX】#002 请求服务端数据(UrlLoader)

    为什么Flex需要请求服务端读取数据,而不是自己读取? Flex 是一门界面语言,主要是做界面展示的,它能实现很多绚丽的效果,这个是传统Web项目部能比的. 但是它对数据库和文件的读写 没有良好的支持 ...

随机推荐

  1. JDBC创建链接的几种方式

    首先,使用java程序访问数据库的前提 数据库的主机地址(ip地址) 端口 数据库用户名 数据库用户密码 连接的数据库 代码: private static String url = "jd ...

  2. oracle utl_http 访问https类型

    https://oracle-base.com/articles/misc/utl_http-and-ssl http://blog.whitehorses.nl/2010/05/27/access- ...

  3. 进程控制(Note for apue and csapp)

    1. Introduction We now turn to the process control provided by the UNIX System. This includes the cr ...

  4. Docker集群管理工具 - Kubernetes 部署记录 (运维小结)

    一.  Kubernetes 介绍 Kubernetes是一个全新的基于容器技术的分布式架构领先方案, 它是Google在2014年6月开源的一个容器集群管理系统,使用Go语言开发,Kubernete ...

  5. Spring集合注入

    1.集合注入 上一篇博客讲了spring得属性注入,通过value属性来配置基本数据类型,通过<property>标签的 ref 属性来配置对象的引用.如果想注入多个数据,那我们就要用到集 ...

  6. java中的io系统详解

    相关读书笔记.心得文章列表 Java 流在处理上分为字符流和字节流.字符流处理的单元为 2 个字节的 Unicode 字符,分别操作字符.字符数组或字符串,而字节流处理单元为 1 个字节,操作字节和字 ...

  7. source insight 添加 python 支持

    从http://www.sourceinsight.com/public/languages/下载Python的配置文件Python.CLF 选择Options > Preferences,单击 ...

  8. Python集成开发工具Pycharm的使用方法:复制,撤销上一步....

    复制行,在代码行光标后,输入Ctrl + d ,即为复制一行,输入多次即为复制多行 撤销上一步操作:Ctrl + z 为多行代码加注释#  代码选中的条件下,同时按住 Ctrl+/,被选中行被注释,再 ...

  9. vue中axios的安装和使用

    有很多时候你在构建应用时需要访问一个 API 并展示其数据.做这件事的方法有好几种,而使用基于 promise 的 HTTP 客户端 axios 则是其中非常流行的一种. 安装包:如果没有安装cnpm ...

  10. Python模块——logging模块

    logging模块简介 logging模块定义的函数和类为应用程序和库的开发实现了一个灵活的事件日志系统.logging模块是Python的一个标准库模块, 由标准库模块提供日志记录API的关键好处是 ...