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

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. http错误代码提示

    1×× 保留 2×× 表示请求成功地接收 3×× 为完成请求客户需进一步细化请求 4×× 客户错误 5×× 服务器错误 200  正常:请求已完成.  201  正常:紧接 POST 命令.  202 ...

  2. 长方体类Java编程题

    1. 编程创建一个Box类(长方体),在Box类中定义三个变量,分别表示长方体的长(length).宽(width)和高(heigth),再定义一个方法void setBox(int l, int w ...

  3. 171. Excel表列序号

    题目:给定一个Excel表格中的列名称,返回其相应的列序号. 例如, A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> ...

  4. bash编程-grep

    grep, egrep, fgrep :输出匹配模式的行 grep:支持基本正则表达式元字符(grep -E相当于egrep) egrep:支持扩展正则表达式元字符(egrep -G相当于grep) ...

  5. 【UWP】使用 Rx 改善 AutoSuggestBox

    在 UWP 中,有一个控件叫 AutoSuggestBox,它的主要成分是一个 TextBox 和 ComboBox.使用它,我们可以做一些根据用户输入来显示相关建议输入的功能,例如百度首页搜索框那种 ...

  6. [数据清洗]-Pandas 清洗“脏”数据(一)

    概要 准备工作 检查数据 处理缺失数据 添加默认值 删除不完整的行 删除不完整的列 规范化数据类型 必要的转换 重命名列名 保存结果 更多资源 Pandas 是 Python 中很流行的类库,使用它可 ...

  7. SDWebImage之SDWebImageDownloader

    SDWebImageDownloader完成了对网络图片的异步下载工作,准确说这个类是一个文件下载的工具类,真正的网络请求是在继承于NSOperation的SDWebImageDownloaderOp ...

  8. C#.Net平台与OPC服务器通讯

    最近,我们Ndolls工作室承接了山大某个自动化控制项目,主要做了一套工控信息化系统,其中有一个功能模块是将系统管理的一部分数据参数发送至OPC服务器,由OPC服务器接收数据后执行相应工控操作.第一次 ...

  9. 下单快发货慢:一个 JOIN SQL 引起 SqlClient 读取数据慢的奇特问题

    最近遇到一个非常奇特的问题,在一个 ASP.NET Core 项目中从 SQL Server 2008 R2 中查询获取 100 条记录竟然耗时 10 多秒,如果是查询本身慢,那到不是什么奇特的问题. ...

  10. Ubuntu 16.04虚拟机调整窗口大小自适应Windows 7

    Windows 7上Ubuntu 16.04虚拟机安装成功后,默认的虚拟机窗口比较小,需要适当调整,才能把虚拟机的屏幕放大, 适合使用,以下介绍调整方法. 安装VMware Tools  启动虚拟机, ...