Java http(post,get)요청 실현
11386 단어 Java
package com.wolaidai.credit.management.utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.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.FileBody;
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.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
public class HttpClientUtil {
protected final Log LOG = LogFactory.getLog(HttpClientUtil.class);
private static HttpClientUtil instance;
protected Charset charset;
private HttpClientUtil(){}
public static HttpClientUtil getInstance() {
return getInstance(Charset.defaultCharset());
}
public static HttpClientUtil getInstance(Charset charset){
if(instance == null){
instance = new HttpClientUtil();
}
instance.setCharset(charset);
return instance;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
/**
* post
*/
public String doPost(String url) throws Exception {
return doPost(url, null, null);
}
public String doPost(String url, Map params) throws Exception {
return doPost(url, params, null);
}
public String doPost(String url, Map params, Map header) throws Exception {
String body = null;
try {
// Post
LOG.debug(" protocol: POST");
LOG.debug(" url: " + url);
HttpPost httpPost = new HttpPost(url.trim());
//
LOG.debug(" params: " + JSON.toJSONString(params));
httpPost.setEntity(new UrlEncodedFormEntity(map2NameValuePairList(params), charset));
// Header
if (header != null && !header.isEmpty()) {
LOG.debug(" header: " + JSON.toJSONString(header));
for (Iterator> it = header.entrySet().iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// ,
body = execute(httpPost);
} catch (Exception e) {
throw e;
}
LOG.debug(" result: " + body);
return body;
}
/**
* postJson
*/
public String doPostJson(String url, Map params) throws Exception {
return doPostJson(url, params, null);
}
public String doPostJson(String url, Map params, Map header) throws Exception {
String json = null;
if (params != null && !params.isEmpty()) {
for (Iterator> it = params.entrySet().iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
Object object = entry.getValue();
if (object == null) {
it.remove();
}
}
json = JSON.toJSONString(params);
}
return postJson(url, json, header);
}
public String doPostJson(String url, String json) throws Exception {
return doPostJson(url, json, null);
}
public String doPostJson(String url, String json, Map header) throws Exception {
return postJson(url, json, header);
}
private String postJson(String url, String json, Map header) throws Exception {
String body = null;
try {
// Post
LOG.debug(" protocol: POST");
LOG.debug(" url: " + url);
HttpPost httpPost = new HttpPost(url.trim());
//
LOG.debug(" params: " + json);
httpPost.setEntity(new StringEntity(json, ContentType.DEFAULT_TEXT.withCharset(charset)));
httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
LOG.debug(" type: JSON");
// Header
if (header != null && !header.isEmpty()) {
LOG.debug(" header: " + JSON.toJSONString(header));
for (Iterator> it = header.entrySet().iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// ,
body = execute(httpPost);
} catch (Exception e) {
throw e;
}
LOG.debug(" result: " + body);
return body;
}
/**
* get
*/
public String doGet(String url) throws Exception {
return doGet(url, null, null);
}
public String doGet(String url, Map header) throws Exception {
return doGet(url, null, header);
}
public String doGet(String url, Map params, Map header) throws Exception {
String body = null;
try {
// Get
LOG.debug("protocol: GET");
HttpGet httpGet = new HttpGet(url.trim());
//
if (params != null && !params.isEmpty()) {
String str = EntityUtils.toString(new UrlEncodedFormEntity(map2NameValuePairList(params), charset));
String uri = httpGet.getURI().toString();
if(uri.indexOf("?") >= 0){
httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str));
}else {
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
}
}
LOG.debug(" url: " + httpGet.getURI());
// Header
if (header != null && !header.isEmpty()) {
LOG.debug(" header: " + header);
for (Iterator> it = header.entrySet().iterator(); it.hasNext();) {
Entry entry = (Entry) it.next();
httpGet.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// ,
body = execute(httpGet);
} catch (Exception e) {
throw e;
}
LOG.debug(" result: " + body);
return body;
}
/**
*
*/
public void doDownload(String url, String path) throws Exception {
download(url, null, path);
}
public void doDownload(String url, Map params, String path) throws Exception {
download(url, params, path);
}
/**
*
*/
public String doUpload(String url, String name, String path) throws Exception {
Map params = new HashMap();
params.put(name, new File(path));
return doUpload(url, params);
}
public String doUpload(String url, Map params) throws Exception {
String body = null;
// Post
HttpPost httpPost = new HttpPost(url.trim());
//
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setCharset(charset);
if (params != null && !params.isEmpty()) {
Iterator it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Object value = params.get(key);
if (value instanceof File) {
FileBody fileBody = new FileBody((File) value);
entityBuilder.addPart(key, fileBody);
} else {
entityBuilder.addPart(key, new StringBody(String.valueOf(value), ContentType.DEFAULT_TEXT.withCharset(charset)));
}
}
}
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
// ,
body = execute(httpPost);
return body;
}
private void download(String url, Map params, String path) throws Exception {
// Get
HttpGet httpGet = new HttpGet(url.trim());
if (params != null && !params.isEmpty()) {
//
String str = EntityUtils.toString(new UrlEncodedFormEntity(map2NameValuePairList(params)));
String uri = httpGet.getURI().toString();
if (uri.indexOf("?") >= 0) {
httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str));
} else {
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
}
}
// ,
downloadFile(httpGet, path);
}
private void downloadFile(HttpRequestBase requestBase, String path) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
CloseableHttpResponse response = httpclient.execute(requestBase);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] b = EntityUtils.toByteArray(entity);
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(path)));
out.write(b);
out.flush();
out.close();
}
EntityUtils.consume(entity);
} catch (Exception e) {
throw e;
} finally {
response.close();
}
} catch (Exception e) {
throw e;
} finally {
httpclient.close();
}
}
private String execute(HttpRequestBase requestBase) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
String body = null;
try {
CloseableHttpResponse response = httpclient.execute(requestBase);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, charset.toString());
}
EntityUtils.consume(entity);
} catch (Exception e) {
throw e;
}finally {
response.close();
}
} catch (Exception e) {
throw e;
} finally {
httpclient.close();
}
return body;
}
private List map2NameValuePairList(Map params) {
if (params != null && !params.isEmpty()) {
List list = new ArrayList();
Iterator it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if(params.get(key) != null) {
String value = String.valueOf(params.get(key));
list.add(new BasicNameValuePair(key, value));
}
}
return list;
}
return null;
}
}
직접 호출 하면 된다
HttpClientUtil.getInstance().doPost(url,Data);
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.