HttpUtils-HttpClient3
그중boot 패키지 아래의 코드는 개인 코드 봉인으로 기능과 함수 이름이 같습니다.apache-common에는 보통 유사한 함수가 있습니다
<dependency>
<groupId>commons-httpclientgroupId>
<artifactId>commons-httpclientartifactId>
<version>3.1version>
dependency>
package cn.seaboot.common.net;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import cn.seaboot.common.bean.P;
import cn.seaboot.common.core.CommonUtils;
import cn.seaboot.common.exception.BizException;
/**
* HttpClient
* @author ChenSS 2018 12 20 5:09:36
*/
public class HttpClientUtils {
/**
*
*/
@SuppressWarnings("deprecation")
public static HttpClient getDefaultHttpClient() {
HttpClientParams defHttpClientParams = new HttpClientParams();
defHttpClientParams.setConnectionManagerTimeout(P.HTTP_CONNECT_TIMEOUT);
defHttpClientParams.setSoTimeout(P.HTTP_RESPONSE_TIMEOUT);
defHttpClientParams.setContentCharset(Charset.defaultCharset().name());
defHttpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(P.HTTP_MAX_RETRY_COUNT, false));
defHttpClientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
// ,
MultiThreadedHttpConnectionManager defConnManager = new MultiThreadedHttpConnectionManager();
defConnManager.setMaxTotalConnections(P.HTTP_MAX_TOTAL_CONNECTION);
defConnManager.setMaxConnectionsPerHost(P.HTTP_MAX_CONNECTION_PER_HOST);
return new HttpClient(defHttpClientParams, defConnManager);
}
/**
* Get
*/
public static GetMethod getGetMethod(String url) {
GetMethod get = new GetMethod(url);
get.setRequestHeader("Connection", "close");
return get;
}
/**
* Post
*/
public static PostMethod getPostMethod(String url) {
PostMethod post = new PostMethod(url);
post.setRequestHeader("Connection", "close");
return post;
}
/**
*
*/
public static void setMethodParams(HttpMethodBase method, String queryString) {
method.setQueryString(queryString);
}
/**
*
*/
public static void setMethodParams(HttpMethodBase method, Map queryString) {
if (CommonUtils.isEmpty(queryString)) {
return;
}
NameValuePair[] pair = new NameValuePair[queryString.size()];
int idx = 0;
for (Entry entry : queryString.entrySet()) {
pair[idx++] = new NameValuePair(entry.getKey(), entry.getValue().toString());
}
method.setQueryString(pair);
}
/**
*
*/
public static void excuteMethod(HttpClient client, HttpMethodBase method) throws HttpException, IOException{
int code = client.executeMethod(method);
if (code != HttpStatus.SC_OK) {
throw new BizException("Request response error:" + code);
}
}
/**
* IO
* @param client
* @param method
* @param is
*/
public static void doPostInputStream(HttpClient client, PostMethod method, InputStream is) throws HttpException, IOException{
method.setRequestEntity(new InputStreamRequestEntity(is));
excuteMethod(client, method);
}
/**
*
* @param client
* @param url
* @param params
* @param files
*/
public static void doPostMultipartFile(HttpClient client, String url, HttpMethodParams params, File... files) throws HttpException, IOException{
PostMethod method = new PostMethod(url);
Part[] parts = new Part[files.length];
File file;
for (int i = 0; i < parts.length; i++) {
file = files[i];
parts[i] = new FilePart(file.getName(), file);
}
MultipartRequestEntity entity = new MultipartRequestEntity(parts, params);
method.setRequestEntity(entity);
excuteMethod(client, method);
}
/**
*
* @param client
* @param url
* @param params
* @param file
* @throws HttpException -
* @throws IOException -
*/
public static void doPostMultipartFile(HttpClient client, String url, HttpMethodParams params, File file) throws HttpException, IOException{
PostMethod method = new PostMethod(url);
Part parts = new FilePart(file.getName(), file);
MultipartRequestEntity entity = new MultipartRequestEntity(new Part[]{parts}, params);
method.setRequestEntity(entity);
excuteMethod(client, method);
}
}
package cn.seaboot.plugin.util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import cn.seaboot.common.core.Now;
import cn.seaboot.common.net.HttpClientUtils;
/**
* POST
* @author ChenSS 2019 1 7 4:23:20
*/
public class HttpUtils {
public static final HttpClient HTTP_CLIENT = HttpClientUtils.getDefaultHttpClient();
/**
* post
* @param url
* @param content XML
*/
public static byte[] doWftPost(String url, String content) throws HttpException, IOException {
PostMethod method = HttpClientUtils.getPostMethod(url);
method.setRequestHeader("Content-Type", "text/xml;utf-8");
method.setRequestEntity(new StringRequestEntity(content, null, "UTF-8"));
HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
return method.getResponseBody();
}
/**
* post
* @param url
* @param content XML
*/
public static String doHkPost(String url, String content) throws HttpException, IOException {
PostMethod method = HttpClientUtils.getPostMethod(url);
method.setRequestHeader("Content-Type", "application/json;utf-8");
method.setRequestEntity(new StringRequestEntity(content, null, "UTF-8"));
HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
return method.getResponseBodyAsString();
}
/**
* post
* @param url
*/
public static String doPost(String url, Map map) throws HttpException, IOException {
PostMethod method = HttpClientUtils.getPostMethod(url);
HttpClientUtils.setMethodParams(method, map);
HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
return method.getResponseBodyAsString();
}
public static void main(String[] args) throws IOException {g";
PostMethod method = HttpClientUtils.getPostMethod(url);
// method.setRequestHeader("Content-Type", "application/json;utf-8");
Map map = new HashMap<>();
map.put("uid",1);
map.put("userId",1);
map.put("msg","----------------");
map.put("createDate",Now.dateTime());
HttpClientUtils.setMethodParams(method, map);
// HttpClientUtils.setMethodParams(method, "content='www.baidu.com'&imgExtName='jpg'&size='5'");
HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
System.out.println(method.getResponseBodyAsString());
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.