java发送http请求
java发送http请求有几种方法
1、HttpURLConnection、URLConnection
使用JDK原生提供的net,无需其他jar包;
2、HttpClient
3、Socket
本文使用依赖于第三方jar包的HttpClient
1、构建发送http所有方法主体
package com.suntek.app.common.utils.http;
import org.apache.commons.lang3.CharEncoding;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
/**
* Comment
*
*/
public class HttpClienProxy {
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
/**
* 连接超时
*/
private static final int HTTP_CONNECTION_TIMEOUT = 4000;
/**
* 请求超时
*/
private static final int HTTP_REQUEST_TIMEOUT = 60000;
private static final Logger LOG = LoggerFactory.getLogger(HttpClienProxy.class);
/**
* 初始化HttpClient
*
* @return
*/
public HttpClient initHttpClient() {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT);
return new DefaultHttpClient(params);
}
public JxHttpResponse sendRequest(HttpClient httpclient, HttpMessage message) throws IOException {
return this.sendRequest(httpclient, message, true);
}
public JxHttpResponse sendRequest(HttpClient httpclient, HttpMessage message, HttpContext context)
throws IOException {
return this.sendRequest(httpclient, message, context, true);
}
public JxHttpResponse sendRequest(HttpClient httpclient, HttpMessage message, boolean closeHttp)
throws IOException {
if (HttpMessage.METHOD_GET.equalsIgnoreCase(message.getMethod())) {
return httpGet(httpclient, message, closeHttp);
} else if (HttpMessage.METHOD_POST.equalsIgnoreCase(message.getMethod())) {
return httpPost(httpclient, message, closeHttp);
} else if (HttpMessage.METHOD_PUT.equalsIgnoreCase(message.getMethod())) {
return httpPut(httpclient, message, closeHttp);
} else if (HttpMessage.METHOD_DELETE.equalsIgnoreCase(message.getMethod())) {
return httpDelete(httpclient, message, closeHttp);
}
return null;
}
public JxHttpResponse sendRequest(HttpClient httpclient, HttpMessage message,
HttpContext context, boolean closeHttp) throws IOException {
if (HttpMessage.METHOD_GET.equalsIgnoreCase(message.getMethod())) {
return httpGet(httpclient, message, context, closeHttp);
} else if (HttpMessage.METHOD_POST.equalsIgnoreCase(message.getMethod())) {
return httpPost(httpclient, message, context, closeHttp);
} else if (HttpMessage.METHOD_PUT.equalsIgnoreCase(message.getMethod())) {
return httpPut(httpclient, message, context, closeHttp);
} else if (HttpMessage.METHOD_DELETE.equalsIgnoreCase(message.getMethod())) {
return httpDelete(httpclient, message, closeHttp);
}
return null;
}
private JxHttpResponse httpGet(HttpClient httpclient, HttpMessage message, boolean closeHttp) {
JxHttpResponse jxHttpResponse = null;
try {
HttpGet httpget = new HttpGet(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httpget, message);
HttpResponse response = httpclient.execute(httpget);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送get请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
private JxHttpResponse httpPost(HttpClient httpclient, HttpMessage message, boolean closeHttp)
throws IOException {
JxHttpResponse jxHttpResponse = null;
try {
HttpPost httppost = new HttpPost(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httppost, message);
HttpEntity entity = new StringEntity(message.getBody(), CharEncoding.UTF_8);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送post请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
private JxHttpResponse httpGet(HttpClient httpclient, HttpMessage message, HttpContext context,
boolean closeHttp) {
JxHttpResponse jxHttpResponse = null;
try {
HttpGet httpget = new HttpGet(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httpget, message);
HttpResponse response = httpclient.execute(httpget, context);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送get请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
private JxHttpResponse httpPost(HttpClient httpclient, HttpMessage message, HttpContext context,
boolean closeHttp) throws IOException {
JxHttpResponse jxHttpResponse = null;
try {
HttpPost httppost = new HttpPost(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httppost, message);
HttpEntity entity = new StringEntity(message.getBody(), CharEncoding.UTF_8);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost, context);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送post请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
/**
* 初始化Header
*
* @param request
* @param message
*/
private void handleRequestHeader(HttpRequestBase request, HttpMessage message) {
List<HttpHeader> list = message.getHeaders();
for (HttpHeader header : list) {
if (!request.containsHeader(header.getKey())) {
request.addHeader(header.getKey(), header.getValue());
}
}
String contentType = message.getContentType();
String attachPath = message.getAttachPath();
if (message.isFrom() && attachPath != null && !"".equals(attachPath)) {
contentType += "; boundary=" + BOUNDARY;
}
// 设置ContentType
if ((request instanceof HttpPut) || (request instanceof HttpPost)) {
if (!contentType.isEmpty()){
request.addHeader("Content-Type", contentType);
}
}
}
private JxHttpResponse httpPut(HttpClient httpclient, HttpMessage message, boolean closeHttp) {
JxHttpResponse jxHttpResponse = null;
try {
HttpPut httpput = new HttpPut(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httpput, message);
HttpEntity entity = new StringEntity(message.getBody(), CharEncoding.UTF_8);
httpput.setEntity(entity);
HttpResponse response = httpclient.execute(httpput);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送put请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
private JxHttpResponse httpPut(HttpClient httpclient, HttpMessage message, HttpContext context, boolean closeHttp) {
JxHttpResponse jxHttpResponse = null;
try {
HttpPut httpput = new HttpPut(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httpput, message);
HttpEntity entity = new StringEntity(message.getBody(), CharEncoding.UTF_8);
httpput.setEntity(entity);
HttpResponse response = httpclient.execute(httpput, context);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送put请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
private JxHttpResponse httpDelete(HttpClient httpclient, HttpMessage message, boolean closeHttp) {
JxHttpResponse jxHttpResponse = null;
try {
HttpDelete httpdelete = new HttpDelete(message.getRequestUrl());
// 初始HTTP请求头
handleRequestHeader(httpdelete, message);
HttpResponse response = httpclient.execute(httpdelete);
if (response != null) {
jxHttpResponse = new JxHttpResponse(
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8)
);
}
} catch (Exception e) {
LOG.error("发送delete请求错误:{}", e);
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return jxHttpResponse;
}
public HttpResponse uploadFile(HttpClient httpclient, HttpMessage message, String filename,
InputStream stream, HttpContext context, boolean closeHttp) throws IOException {
HttpResponse response = null;
try {
HttpPost httppost = new HttpPost(message.getRequestUrl());
// 初始HTTP请求头
//handleRequestHeader(httppost, message);
InputStreamBody body = new InputStreamBody(stream, filename);
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", body);
List<HttpBodyParam> params = message.getParams();
if (params!=null && params.size()>0) {
StringBody comment = null;
for (HttpBodyParam httpBodyParam : params) {
if (httpBodyParam==null) {
continue;
}
comment = new StringBody(httpBodyParam.getValue());
entity.addPart(httpBodyParam.getName(), comment);//设置请求后台的普通参数
}
}
httppost.setEntity(entity);
response = httpclient.execute(httppost, context);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpclient != null && closeHttp) {
httpclient.getConnectionManager().shutdown();
}
}
return response;
}
/**
* 初始化client
* 不添加请求超时参数
* 添加请求超时参数导致httpclient读取返回数据异常
* @return
*/
public HttpClient initHttpClientWithoutSoTimeOut() {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECTION_TIMEOUT);
return new DefaultHttpClient(params);
}
}
2、构建http消息头
package com.suntek.app.common.utils.http;
/**
* HTTP消息头
*
*/
public class HttpHeader {
private String key = "";
private String value = "";
public HttpHeader() {
}
public HttpHeader(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
3、构建http消息体
package com.suntek.app.common.utils.http;
import java.io.Serializable;
/**
* HTTP消息体
*
*/
public class HttpBodyParam implements Serializable {
private static final long serialVersionUID = 1L;
private String name = "";
private String value = "";
public HttpBodyParam() {
}
public HttpBodyParam(String name, String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
4、构建http消息(整体)
package com.suntek.app.common.utils.http;
import java.util.ArrayList;
import java.util.List;
/**
* HTTP消息
*
*/
public class HttpMessage {
public static final String METHOD_GET = "GET";
public static final String METHOD_PUT = "PUT";
public static final String METHOD_POST = "POST";
public static final String METHOD_DELETE = "DELETE";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_HOST = "Host";
public static final String HEADER_USER_AGENT = "user-Agent";
public static final String AGENT_NAME = "Http-Client-Tool";
public static final String CONTENT_TYPE_FORM = "form";
public static final String CONTENT_TYPE_TEXT_UTF8 = "text/plain; charset=utf-8";
public static final String CONTENT_TYPE_JSON = "application/json";
private String requestUrl = "";
private String method = "";
private String body = "";
private String contentType = "";
private boolean isFrom = true;
private String attachName = "";
private String attachPath = "";
private String protocol = "";
public static final String HTTP = "http";
public static final String HTTPS = "https";
/**
* 消息头集合
*/
List<HttpHeader> headers = null;
/**
* 消息体集合
*/
List<HttpBodyParam> params = null;
public HttpMessage() {
headers = new ArrayList<HttpHeader>();
params = new ArrayList<HttpBodyParam>();
}
public void addHeader(String key, String value) {
HttpHeader header = new HttpHeader(key, value);
headers.add(header);
}
public void addBodyParam(String name, String value) {
HttpBodyParam bodyParam = new HttpBodyParam(name, value);
params.add(bodyParam);
}
/**
* 获取URL地址
*
* @return
*/
public String getRequestUrl() {
return requestUrl;
}
public void setRequestUrl(String requestUrl) {
this.requestUrl = requestUrl;
}
public String getProtocolStr() {
String headS = "://";
this.protocol = requestUrl.substring(0, requestUrl.indexOf(headS));
return protocol;
}
/**
* 获取请求相对路径
*
* @return
*/
public String getRequestPath() {
// http://localhost:8090/ap/service/index.jsp
String headS = "://";
String lastPart = requestUrl.substring(requestUrl.indexOf(headS) + headS.length());
String path = lastPart.substring(lastPart.indexOf("/"));
return path;
}
/**
* 获取主机地址
*
* @return
*/
public String getHost() {
String headS = "://";
String lastPart = requestUrl.substring(requestUrl.indexOf(headS) + headS.length());
String host = lastPart.substring(0, lastPart.indexOf("/"));
if (host.indexOf(":") > 0) {
return host.split(":")[0];
}
return host;
}
/**
* 获取主机端口
*
* @return
*/
public int getPort() {
String headS = "://";
String lastPart = requestUrl.substring(requestUrl.indexOf(headS) + headS.length());
String host = lastPart.substring(0, lastPart.indexOf("/"));
if (host.indexOf(":") > 0) {
return Integer.parseInt(host.split(":")[1]);
}
return 80;
}
public int getBodyLength() {
return body.length();
}
public boolean isGzip() {
for (HttpHeader header : headers) {
if (header.getKey().equalsIgnoreCase("Content-Encoding")
&& header.getValue().equalsIgnoreCase("gzip")) {
return true;
}
}
return false;
}
public void setHeaders(List<HttpHeader> headers) {
this.headers = headers;
}
public List<HttpHeader> getHeaders() {
return headers;
}
public List<HttpBodyParam> getParams() {
return params;
}
public void setParams(List<HttpBodyParam> params) {
this.params = params;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method.toUpperCase();
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAttachPath() {
return attachPath;
}
public void setAttachPath(String attachPath) {
this.attachPath = attachPath;
}
public boolean isFrom() {
return isFrom;
}
public void setFrom(boolean isFrom) {
this.isFrom = isFrom;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentTypeReal() {
String[] arr = contentType.split(";");
return arr[0].trim();
}
public String getCharset() {
String[] arr = contentType.split(";");
return arr[1].trim().split("=")[1].trim();
}
public String getAttachName() {
return attachName;
}
public void setAttachName(String attachName) {
this.attachName = attachName;
}
public static void main(String[] args) {
String test = "https://localhost:8090/ap/service/index.jsp";
String headS = "://";
System.out.println(test.substring(0, test.indexOf(headS)));
}
}
5、构建消息响应实体
package com.suntek.app.common.utils.http;
/**
* @author wb
* @version 1.0
* @date 2022/12/29 16:13
*/
public class JxHttpResponse {
private Integer statusCode;
private String reasonPhrase;
private String content;
public JxHttpResponse(Integer statusCode, String reasonPhrase, String content) {
this.statusCode = statusCode;
this.reasonPhrase = reasonPhrase;
this.content = content;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public String getReasonPhrase() {
return reasonPhrase;
}
public void setReasonPhrase(String reasonPhrase) {
this.reasonPhrase = reasonPhrase;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
7、调用发送http请求方法
//发送http请求
private void sendTo(String uri, String body) {
LOG.info("反向开户报文[BbossService.sendTo] the uri : {}, the body : {}", uri, body);
HttpMessage httpMessage = buildHttpMessage(uri, body);
JxHttpResponse httpResponse;
NotifyReverseUserResponse notifyReverseUserResponse;
try {
HttpClienProxy proxy = new HttpClienProxy();
HttpClient client = proxy.initHttpClient();
httpResponse = proxy.sendRequest(client, httpMessage);
if (httpResponse != null) {
String data = httpResponse.getContent();
notifyReverseUserResponse = JSONObject.parseObject(data, NotifyReverseUserResponse.class);
Integer code = httpResponse.getStatusCode();
if (LOG.isDebugEnabled()) {
LOG.debug("the response code : {}, \r\n the response content : {}",
code, notifyReverseUserResponse);
}
} else {
}
} catch (Exception e) {
LOG.error("occur Exception:{}", e.getMessage(), e);
}
}
//http消息传值
private HttpMessage buildHttpMessage(String uri, String body) {
List<HttpHeader> headers = new LinkedList<>();
HttpHeader httpHeader = new HttpHeader();
headers.add(httpHeader);
HttpMessage httpMessage = new HttpMessage();
httpMessage.setRequestUrl(uri);
httpMessage.setMethod(HttpMessage.METHOD_POST);
httpMessage.setContentType(HttpMessage.CONTENT_TYPE_JSON);
httpMessage.setBody(body);
httpMessage.setHeaders(headers);
return httpMessage;
}
8、接收消息的json实体类
package com.suntek.app.common.entity.reverse.response;
import java.io.Serializable;
/**
* @author wb
* @version 1.0
* @date 2022/12/29 19:58
*/
public class NotifyReverseUserResponse implements Serializable {
private Integer code;
private String msg;
private Long timestamp;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return "NotifyReverseUserResponse{" +
"code=" + code +
", msg='" + msg + '\'' +
", timestamp=" + timestamp +
'}';
}
}