JAVA http 接口请求方式
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
HttpClient实现Http请求的步骤如下:
创建CloseableHttpClient
创建HttpGet或HttpPost对象,传入url,有参数就传入参数
httpclient执行请求,用HttpResponse接受返回数据
使用HttpEntity在response中获取entity
将entity转化成string,再规范成JsonObject
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* https://raw.github.com/wjosdejong/httputil/master/src/com/almende/util/HttpUtil.java
*
* @project baidamei
* @author cevencheng <cevencheng@gmail.com>
* @create 2012-11-17 下午2:35:38
*/
public class HttpUtil {
/**
* Send a get request
* @param url
* @return response
* @throws IOException
*/
static public String get(String url) throws IOException {
return get(url, null);
}
/**
* Send a get request
* @param url Url as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
static public String get(String url,
Map<String, String> headers) throws IOException {
return fetch("GET", url, null, headers);
}
/**
* Send a post request
* @param url Url as string
* @param body Request body as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
static public String post(String url, String body,
Map<String, String> headers) throws IOException {
return fetch("POST", url, body, headers);
}
/**
* Send a post request
* @param url Url as string
* @param body Request body as string
* @return response Response as string
* @throws IOException
*/
static public String post(String url, String body) throws IOException {
return post(url, body, null);
}
/**
* Post a form with parameters
* @param url Url as string
* @param params map with parameters/values
* @return response Response as string
* @throws IOException
*/
static public String postForm(String url, Map<String, String> params)
throws IOException {
return postForm(url, params, null);
}
public static JSONObject postForForm3(String url, Map<String, String> parms) {
HttpPost httpPost = new HttpPost(url);
ArrayList<BasicNameValuePair> list = new ArrayList<>();
parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
if (Objects.nonNull(parms) && parms.size() >0)
{
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
}
InputStream content = httpPost.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readLine = bufferedReader.readLine();
String s = URLDecoder.decode(readLine, "UTF-8");
System.out.println("readLine===================================" + readLine);
System.out.println("s==========================================" + s);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
return jsonObject;
}catch (IOException e) {
e.printStackTrace();
}finally {
if (Objects.nonNull(httpClient)){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 基于form 表单进行传送数据
* @param url
* @param parms
* @return
* @throws Exception
*/
public static JSONObject postForForm(String url, Map<String, String> parms) throws Exception{
HttpPost httpPost = new HttpPost(url);
ArrayList<BasicNameValuePair> list = new ArrayList<>();
parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
try (CloseableHttpClient httpClient = createHttpClient()) {
if (Objects.nonNull(parms) && parms.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
}
InputStream content = httpPost.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readLine = bufferedReader.readLine();
String s = URLDecoder.decode(readLine, "UTF-8");
/* System.out.println("readLine===================================" + readLine);
System.out.println("s==========================================" + s); */
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
return jsonObject;
}
catch (IOException e) {
e.printStackTrace();
}finally {
if (Objects.nonNull(httpClient)){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 将https 请求方式加为可信认证方式
* @param APIUrl
* @param jsonObjects
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws KeyManagementException
*/
public static String postMan2(String APIUrl, JSONObject jsonObjects ) throws Exception
{
try (CloseableHttpClient httpClient = createHttpClient()) {
HttpPost httpPost = new HttpPost(APIUrl);
httpPost.setHeader("Accept","application/x-www-form-urlencoded");
//JSONObject jsonObjects = new JSONObject();
// 传值时传递的是json字符串,这样的好处是在服务端无需建立参数模型,直接接收String,便于后期维护。
StringEntity stringEntity = new StringEntity(jsonObjects.toJSONString(),"utf-8");
httpPost.setEntity(stringEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
//System.out.printf(result);
return result;
}
}
}
/**
* 将https 请求方式加为可信认证方式
* @param APIUrl
* @param jsonObjects
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws KeyManagementException
*/
public static String postMan(String APIUrl, JSONObject jsonObjects ) throws Exception
{
try (CloseableHttpClient httpClient = createHttpClient()) {
HttpPost httpPost = new HttpPost(APIUrl);
httpPost.setHeader("Accept","application/x-www-form-urlencoded");
//JSONObject jsonObjects = new JSONObject();
// 传值时传递的是json字符串,这样的好处是在服务端无需建立参数模型,直接接收String,便于后期维护。
StringEntity stringEntity = new StringEntity(jsonObjects.toJSONString(),"utf-8");
httpPost.setEntity(stringEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
//System.out.printf(result);
return result;
}
}
}
private static CloseableHttpClient createHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, (chain, authType) -> true)
.build();
SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null,
new NoopHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslSf).build();
}
/**
* Post a form with parameters
* @param url Url as string
* @param params Map with parameters/values
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
static public String postForm(String url, Map<String, String> params,
Map<String, String> headers) throws IOException {
// set content type
if (headers == null) {
headers = new HashMap<String, String>();
}
headers.put("Content-Type", "application/x-www-form-urlencoded");
// parse parameters
String body = "";
if (params != null) {
boolean first = true;
for (String param : params.keySet()) {
if (first) {
first = false;
} else {
body += "&";
}
String value = params.get(param);
body += URLEncoder.encode(param, "UTF-8") + "=";
body += URLEncoder.encode(value, "UTF-8");
}
}
return post(url, body, headers);
}
/**
* Send a put request
* @param url Url as string
* @param body Request body as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
static public String put(String url, String body,
Map<String, String> headers) throws IOException {
return fetch("PUT", url, body, headers);
}
/**
* Send a put request
* @param url Url as string
* @return response Response as string
* @throws IOException
*/
static public String put(String url, String body) throws IOException {
return put(url, body, null);
}
/**
* Send a delete request
* @param url Url as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
static public String delete(String url,
Map<String, String> headers) throws IOException {
return fetch("DELETE", url, null, headers);
}
/**
* Send a delete request
* @param url Url as string
* @return response Response as string
* @throws IOException
*/
static public String delete(String url) throws IOException {
return delete(url, null);
}
/**
* Append query parameters to given url
* @param url Url as string
* @param params Map with query parameters
* @return url Url with query parameters appended
* @throws IOException
*/
static public String appendQueryParams(String url,
Map<String, String> params) throws IOException {
String fullUrl = new String(url);
if (params != null) {
boolean first = (fullUrl.indexOf('?') == -1);
for (String param : params.keySet()) {
if (first) {
fullUrl += '?';
first = false;
} else {
fullUrl += '&';
}
String value = params.get(param);
fullUrl += URLEncoder.encode(param, "UTF-8") + '=';
fullUrl += URLEncoder.encode(value, "UTF-8");
}
}
return fullUrl;
}
/**
* Retrieve the query parameters from given url
* @param url Url containing query parameters
* @return params Map with query parameters
* @throws IOException
*/
static public Map<String, String> getQueryParams(String url)
throws IOException {
Map<String, String> params = new HashMap<String, String>();
int start = url.indexOf('?');
while (start != -1) {
// read parameter name
int equals = url.indexOf('=', start);
String param = "";
if (equals != -1) {
param = url.substring(start + 1, equals);
} else {
param = url.substring(start + 1);
}
// read parameter value
String value = "";
if (equals != -1) {
start = url.indexOf('&', equals);
if (start != -1) {
value = url.substring(equals + 1, start);
} else {
value = url.substring(equals + 1);
}
}
params.put(URLDecoder.decode(param, "UTF-8"),
URLDecoder.decode(value, "UTF-8"));
}
return params;
}
/**
* Returns the url without query parameters
* @param url Url containing query parameters
* @return url Url without query parameters
* @throws IOException
*/
static public String removeQueryParams(String url)
throws IOException {
int q = url.indexOf('?');
if (q != -1) {
return url.substring(0, q);
} else {
return url;
}
}
/**
* Send a request
* @param method HTTP method, for example "GET" or "POST"
* @param url Url as string
* @param body Request body as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
static public String fetch(String method, String url, String body,
Map<String, String> headers) throws IOException {
// connection
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// method
if (method != null) {
conn.setRequestMethod(method);
}
// headers
if (headers != null) {
for (String key : headers.keySet()) {
conn.addRequestProperty(key, headers.get(key));
}
}
// body
if (body != null) {
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
}
// response
InputStream is = conn.getInputStream();
String response = streamToString(is);
is.close();
// handle redirects
if (conn.getResponseCode() == 301) {
String location = conn.getHeaderField("Location");
return fetch(method, location, body, headers);
}
return response;
}
/**
* Read an input stream into a string
* @param in
* @return
* @throws IOException
*/
static public String streamToString(InputStream in) throws IOException {
BufferedReader inR = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuffer out = new StringBuffer();
String line = "";
while ((line = inR.readLine()) != null){
out.append(line);
}
return out.toString();
}
}
再牛逼的梦想,也抵不住我傻逼似的坚持!别在该奋斗的年纪,贪图安逸。 今天多学一些知识,明天开发的速度就更快一下。后天你就会变得更好。