httpmime実現http要求-post及びget要求、ファイルダウンロードなど
要約
webプロジェクトではないファイルをダウンロードし、appheのhttpmimeツールを使ってhttpに関連した操作を要請します。
本題
必要:非webプロジェクトを実現し、ファイルダウンロードまたはhttp要求を行う。
1、関連pom依存追加
3、logbackに関する依存
webプロジェクトではないファイルをダウンロードし、appheのhttpmimeツールを使ってhttpに関連した操作を要請します。
本題
必要:非webプロジェクトを実現し、ファイルダウンロードまたはhttp要求を行う。
1、関連pom依存追加
org.apache.httpcomponents
httpmime
4.5.5
2、関連ツールコードの要求package com.lanxuewei.utils.file.deepwise;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.lanxuewei.utils.io.IOUtils;
/**
* @author lanxuewei Create in 2018/9/19 16:54
* Description: http
*/
public class HttpClientHelper {
private static final Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
/**
* http post ,json
*
* @param map
* @param url url
* @return
* @throws IOException
*/
public String postWithHttp(Map<String, Object> map, String url) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
return EntityUtils.toString(resEntity);
}
} catch (IOException e) {
logger.error("", e);
}
return "";
}
/**
* post
*
* @param map
* @param url url
* @param token token
* @return
* @throws IOException
*/
public String postFormWithHttp(Map<String, Object> map, String url, String token) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("token", token);
ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Map.Entry<String, Object> entry : map.entrySet()) {
builder.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), contentType));
}
HttpEntity httpEntity = null;
try {
httpEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
} catch (UnsupportedEncodingException e) {
logger.error("", e);
}
httpPost.setEntity(httpEntity);
return execute(client, httpPost);
}
/**
* get
*
* @param map
* @param url url
* @param token token
* @return
* @throws IOException
*/
public String getWithHttp(Map<String, Object> map, String url, String token) {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
//
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
httpGet.setConfig(requestConfig);
httpGet.setHeader("token", token);
return execute(client, httpGet);
}
/**
*
*
* @param client client
* @param httpPost httpPost
* @return
*/
private String execute(CloseableHttpClient client, HttpRequestBase httpPost) {
if (client == null || httpPost == null) {
return "";
}
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
return EntityUtils.toString(resEntity);
}
} catch (Exception e) {
logger.error("", e);
} finally {
IOUtils.safeClose(response);
}
return "";
}
/**
*
*
* @param url url
* @param token token
* @return
* @throws IOException
*/
public boolean downFileByGet(String url, String token, File targetFile) {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
//
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
httpGet.setConfig(requestConfig);
httpGet.setHeader("token", token);
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet);
} catch (IOException e) {
logger.error("", e);
}
assert response != null;
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
// org.apache.commons.io.IOUtils.copy(response.getEntity().getContent(), new FileOutputStream(targetFile));
response.getEntity().writeTo(new FileOutputStream(targetFile)); //
} catch (IOException e) {
logger.error("", e);
}
}
return true;
}
}
説明:1、本コードではログはlogback、json関連解析などでfastjsonを採用しています。直接コードをコピーするとエラーが発生しますので、関連した依存性を導入する必要があります。この文章の内容とは関係がないので、前の席の依存度は与えられませんでした。またはログを使用しないか?これは筆者の需要がtoken認証を必要としているため、読者が3、urlを完全なインターフェースアクセス経路として削除または保留する必要があります。http://localhost:8080/index 4、要求中のパラメータはmapを使って入ってきます。すなわち、パラメータ名-パラメータ値キーの値対5、最後の関数downFileByGetはファイルダウンロード関数です。3、logbackに関する依存
ch.qos.logback
logback-classic
1.1.11
com.alibaba
fastjson
1.2.39
:以前は手動でタイムアウト時間を設定していませんでしたので、長い時間無応答を要求すると、ずっと渋滞問題が発生するのを待つことになります。タイムアウト設定コードを追加しました。以上のコードは追加されました。以下に手動でタイムアウトコードブロックを設定します。コードは以下の通りです。//
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);