對HttpClient的一些封裝方法
摘自專案中的util,利用httpclient傳送get、post請求,上傳、下載檔案,可以直接拿去當作util類來使用。
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* HttpClient 封裝
* Created by Administrator on 2016/12/7.
*/
public class SimpleHttpClient {
public static final Logger logger = LoggerFactory.getLogger(SimpleHttpClient.class);
public static final Integer cache_size = 4096;
public static InputStream invokePost4Stream(String url, Map<String, Object> params, Map<String, String> headers,int timeout) throws IOException {
HttpClient hc = new HttpClient();
PostMethod post = new PostMethod(url);
if (headers != null) {
Set<Map.Entry<String, String>> entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
post.addRequestHeader(entry.getKey(),String.valueOf(entry.getValue()));
}
}
post.getParams().setContentCharset("UTF-8");
if (params != null) {
Set<Map.Entry<String, Object>> entrys = params.entrySet();
for (Map.Entry<String, Object> entry : entrys) {
post.addParameter(entry.getKey(),String.valueOf(entry.getValue()));
}
}
try {
hc.getParams().setSoTimeout(timeout);
hc.executeMethod(post);
return post.getResponseBodyAsStream();
} finally {
// post.releaseConnection();
}
}
public static HttpResponse httpGetHttpResponse(String url) throws IOException {
String uuid = UUID.randomUUID().toString();
logger.info("http get request uuid={},url={}", uuid, url);
//get請求返回結果
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
return response;
} catch (IOException e) {
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(client);
}
}
public static JSONObject invokePost(String urlString, JSONObject json) throws IOException {
// Configure and open a connection to the site you will send the request
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
// 設定doOutput屬性為true表示將使用此urlConnection寫入資料
urlConnection.setDoOutput(true);
// 定義待寫入資料的內容型別,我們設定為application/x-www-form-urlencoded型別
urlConnection.setRequestProperty("content-type", "application/json");
// 得到請求的輸出流物件
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
// 把資料寫入請求的Body
out.write(json.toJSONString());
out.flush();
out.close();
// 從伺服器讀取響應
InputStream inputStream = urlConnection.getInputStream();
String encoding = urlConnection.getContentEncoding();
String body = IOUtils.toString(inputStream, encoding);
JSONObject result = JSONObject.parseObject(body);
return result;
}
public static JSONObject invokePost(String urlString, JSONObject json, Map<String, String> headers) throws IOException {
// Configure and open a connection to the site you will send the request
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
// 設定doOutput屬性為true表示將使用此urlConnection寫入資料
urlConnection.setDoOutput(true);
// 定義待寫入資料的內容型別,我們設定為application/x-www-form-urlencoded型別
urlConnection.setRequestProperty("content-type", "application/json");
if(headers != null){
Set<Map.Entry<String, String>> entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
urlConnection.setRequestProperty(entry.getKey(),String.valueOf(entry.getValue()));
}
}
// 得到請求的輸出流物件
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
// 把資料寫入請求的Body
out.write(json.toJSONString());
out.flush();
out.close();
// 從伺服器讀取響應
InputStream inputStream = urlConnection.getInputStream();
String encoding = urlConnection.getContentEncoding();
String body = IOUtils.toString(inputStream, encoding);
JSONObject result = JSONObject.parseObject(body);
return result;
}
public static InputStream httpGet4Stream(String url) throws IOException {
return httpGet4Stream(url, null);
}
public static InputStream httpGet4Stream(String url, Map<String, String> headers) throws IOException {
String uuid = UUID.randomUUID().toString();
logger.info("http get request uuid={},url={}", uuid, url);
//get請求返回結果
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
if (headers != null) {
Set<Map.Entry<String, String>> entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
request.setHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
return entity.getContent();
} catch (IOException e) {
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(client);
}
}
/**
* 下載檔案
*
* @param url
* @param bao
* @return
* @throws IOException
*/
public static String httpGetFile(String url, ByteArrayOutputStream bao) throws IOException {
String fileName = null;
String uuid = UUID.randomUUID().toString();
logger.info("http get request uuid={},url={}", uuid, url);
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
/**請求傳送成功,並得到響應**/
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
long length = entity.getContentLength();
if (length <= 0) {
logger.error("下載檔案不存在!");
return fileName;
}
byte[] buffer = new byte[cache_size];
int readLength;
while ((readLength = in.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
bao.write(bytes);
}
bao.flush();
fileName = getFileName(response);
}
return fileName;
} catch (IOException e) {
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(client);
}
}
public static HttpResponse httpPostHttpResponse(String url, JSONObject jsonParam) throws IOException {
String uuid = UUID.randomUUID().toString();
logger.info("http post request uuid={},url={},param={}", uuid, url, jsonParam);
//post請求返回結果
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
try {
checkJsonParam(jsonParam, request);
HttpResponse response = client.execute(request);
return response;
} catch (IOException e) {
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(client);
}
}
private static void checkJsonParam(JSONObject jsonParam, HttpPost method) {
if (null != jsonParam) {
//解決中文亂碼問題
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
}
/**
* post請求
*
* @param url
* @param jsonParam
* @param timeout
* @return
* @throws IOException
*/
public static JSONObject httpPost(String url, JSONObject jsonParam, Integer timeout) throws IOException {
String uuid = UUID.randomUUID().toString();
logger.info("http post request uuid={},url={},param={}", uuid, url, jsonParam);
//post請求返回結果
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
JSONObject jsonResult = null;
HttpPost request = new HttpPost(url);
try {
if (timeout != null && timeout > 0) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeout)
.setConnectTimeout(timeout)
.setSocketTimeout(timeout).build();
request.setConfig(requestConfig);
}
checkJsonParam(jsonParam, request);
HttpResponse result = httpClient.execute(request);
/**請求傳送成功,並得到響應**/
if (result.getStatusLine().getStatusCode() == 200) {
/**讀取伺服器返回過來的json字串資料**/
String str = EntityUtils.toString(result.getEntity());
/**把json字串轉換成json物件**/
jsonResult = JSONObject.parseObject(str);
}
} catch (IOException e) {
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(httpClient);
}
logger.info("http post response uuid={},response={}", uuid, jsonResult);
return jsonResult;
}
/**
* post請求
*
* @param url
* @param jsonParam
* @return
* @throws IOException
*/
public static JSONObject httpPost(String url, JSONObject jsonParam) throws IOException {
return httpPost(url, jsonParam, null);
}
/**
* 上傳檔案
*
* @param url
* @param file
* @return
* @throws IOException
*/
public static JSONObject httpPost(String url, File file) throws IOException {
String uuid = UUID.randomUUID().toString();
logger.info("http post request uuid={},url={},file={}", uuid, url, file);
//post請求返回結果
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
JSONObject jsonResult = null;
HttpPost request = new HttpPost(url);
try {
if (null != file) {
FileBody binFileBody = new FileBody(file);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addPart(file.getName(), binFileBody);
// 設定上傳的其他引數
// setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
request.setEntity(reqEntity);
}
HttpResponse result = httpClient.execute(request);
/**請求傳送成功,並得到響應**/
if (result.getStatusLine().getStatusCode() == 200) {
/**讀取伺服器返回過來的json字串資料**/
String str = EntityUtils.toString(result.getEntity());
/**把json字串轉換成json物件**/
jsonResult = JSONObject.parseObject(str);
}
} catch (IOException e) {
httpClient.close();
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(httpClient);
}
logger.info("http post response uuid={},response={}", uuid, jsonResult);
return jsonResult;
}
/**
* 傳送get請求
*
* @param url 路徑
* @return
*/
public static JSONObject httpGet(String url) throws IOException {
String uuid = UUID.randomUUID().toString();
logger.info("http get request uuid={},url={}", uuid, url);
//get請求返回結果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
/**請求傳送成功,並得到響應**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
logger.debug("response : " + response);
/**讀取伺服器返回過來的json字串資料**/
String strResult = EntityUtils.toString(response.getEntity());
/**把json字串轉換成json物件**/
jsonResult = JSONObject.parseObject(strResult);
}
} catch (IOException e) {
throw e;
} finally {
request.releaseConnection();
CloseUtil.close(client);
}
logger.info("http get response uuid={},response={}", uuid, jsonResult);
return jsonResult;
}
private static String getFileName(HttpResponse response) {
Header contentHeader = response.getFirstHeader("Content-Disposition");
String filename = null;
if (contentHeader != null) {
HeaderElement[] values = contentHeader.getElements();
if (values.length == 1) {
NameValuePair param = values[0].getParameterByName("filename");
if (param != null) {
try {
filename = new String(param.getValue().toString().getBytes(), "utf-8");
filename = URLDecoder.decode(param.getValue(), "utf-8");
filename = param.getValue();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return filename;
}
}
相關推薦
對HttpClient的一些封裝方法
摘自專案中的util,利用httpclient傳送get、post請求,上傳、下載檔案,可以直接拿去當作util類來使用。 import com.alibaba.fastjson.JSONObject; import org.apache.commons.ht
使用spring-data-redis進行對redis的操作,封裝的一些操作方法
這個算是工作筆記吧,因為是我的實際工作內容 spring-data-redis api地址 http://docs.spring.io/spring-data/redis/docs/current/api/ 依賴maven包(當前spring-data-
HttpClient封裝方法
string byte llb lse method sin ddr () sync //post請求 public static string PostRequest(string url, HttpContent data) {
匿名對象 、封裝(private)、this關鍵詞、構造方法
參數的傳遞 成員變量 匿名 重載 導致 系統 name 復用性 應用 1.匿名對象 匿名對象:沒有名字的對象 應用場景:調用方法,僅僅只調用一次的時候;匿名對象可以作為實際參數的傳遞??例;new Student ().name; 2.封裝(private) 封裝概述:指
httpclient常規封裝的方法
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId>
JS對時間的一些操作方法
//當前時間要增加的秒數 date.AddSeconds(-1); Date.prototype.AddSeconds = function (Seconds){ var date = this; return new Dat
基於顯示等待封裝的一些常用方法
import os import time from PIL import Image from selenium import webdriver from appium import webdriver as app from selenium.common.exceptions import *
對敏捷軟體開發方法的一些體會(轉貼)
我覺得推行一個新技術最大的阻力還是來自程式設計師自身管理層一般不會關心開發方法和技術細節的問題struts的流行恐怕主要也是技術人員發自內心的認可和推崇造成的吧畢竟這牽涉到他的切身利益(工作效率、成就感、樂趣。。。)同樣的道理,單元測試和其他敏捷方法也要首先打動技術人員的心,
關於js封裝的一些簡單方法
對於jquery我們都不陌生,都知道jquery的強大之處;寫的少,做的多。那我們就簡單看一下關於jquery的基本操作選擇器對於一個盒子<div id="box">盒子</div>用jQuery就是$("#box")就可以了那麼用原生的js就是doc
關於apicloud開發中對vue和ajax方法的封裝
先上圖封裝js//封裝方法 function Ardo(id, mydata, pagesize){ var ardo = new Vue({ el: '#'+id, data: { msg: '',
mysqli 對象風格封裝
const 函數 truct 多條 color ret more username 獲取 <?php/* $obj=new obj(param...)$obj->set_charset()$obj->connect_errno$obj->connec
面向對象抽象封裝
控制語句 菜單 修飾符 ret setters pri 面向對象設計 類型 setter ? 第一章第一次課? 使用類圖如何描述設計 - private(私有) 屬性+ public(公共) 方法訪問修飾符:缺省(默認),只能被同一個包中的類訪問private(私有的
1.1 面向對象 對象引用與方法引用
out 對象 進行 name static [] 年齡 屬性 面向 public class Demo1 { public static void main(String[] args) { //定義的類需要依靠對象進行操作,給出對象的格式 //類名稱 對象名稱
判斷對象存活的方法
靜態屬性 native方法 類型 本地方法棧 判斷 roo 軟引用 root 棧幀 1. 引用計數法:給對象添加一個引用計數器,每當一個地方引用它,計數器值加1;當引用失效時,計數器值就減1 2. 可達性分析法:當一個對象到GC Roots沒有任何引用鏈相連時,該對象被判斷
合並數組封裝方法
數組 function arrayadd($a,$b){ //根據鍵名獲取兩個數組的交集 $arr=array_intersect_key($a, $b); //遍歷第二個數組,如果鍵名不存在與第一個數組,將數組元素增加到第一個數組 fore
easyUi的一些常用方法
pager pan color 方法 enum easy 選中 get gen 目錄: 1.獲取表格的pageNumber和pageSize 2.獲取下拉列表的選中值 3. 1.獲取表格的pageNumber和pageSize var pageNumber = $
Qt官方對OpenSSL的編譯方法的描述
lin openssl hack ons version building nss ssl 編譯 https://wiki.qt.io/MSYS2http://wiki.qt.io/Compiling_OpenSSL_with_MinGWhttps://wiki.qt.io
對象的封裝
可靠 信息 服務 限制 mil div 一定的 trac wrap 封裝是指依照信息屏蔽的原則,把對象的屬性和操作結合在一起,構成一個獨立的對象。 通過限制對屬性和操作的訪問權限。能夠將屬性“隱藏”在對象內部。對外提供一定的接口,在對象之外僅僅能通過接口對
JS面向對象(封裝,繼承)
通過 ray 混合 字母 顯示 彈出 pan rip http 在六月份找工作中,被問的最多的問題就是: js面向對象,繼承,封裝,原型鏈這些,你了解多少? 額,,,我怎麽回答呢, 只能說,了解一些,不多不少,哈哈哈哈,當然,這是玩笑話。 不過之前學過java,來理解這些還
JavaSE入門學習23:Java面向對象之構造方法
ons 抽象類 什麽 ont 機會 語法 好的 error return 學了JavaSE面向對象這一部分,也該對構造方法做一個總結了。 一構造方法 在多數情況下,初始化一個對象的終於步驟是去調用這個對象的構造方法。構造