一、hutool工具包實(shí)現(xiàn)
1、get請(qǐng)求
// url:鏈接地址,params:填充在url中的參數(shù), useProxy:是否使用代理
// proxyHost:代理地址, proxyPort:代理端口號(hào)
public String httpGet(String url, String params, String useProxy) {
String requestUrl = url;
if (StringUtils.isNotBlank(params)) {
requestUrl = url + "?" + params;
}
String respData = null;
log.info("httpGet req is 【{}】", params);
HttpRequest httpRequest = HttpRequest.get(requestUrl).timeout(socketTimeout).header("token",
"application/json");
if ("Y".equalsIgnoreCase(useProxy)) {
log.info(String.format("使用代理"));
httpRequest.setProxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
}
respData = httpRequest.execute().body();
log.info(String.format("HttpsUtil:httpGet | 請(qǐng)求信息:%s | 響應(yīng)信息: %s", httpRequest.getUrl(), respData));
return respData;
}
2、post請(qǐng)求
// url:鏈接地址,params:填充在url中的參數(shù), sendBodyData:body, useProxy:是否使用代理
// proxyHost:代理地址, proxyPort:代理端口號(hào)
public String httpPost(String url, String params, String sendBodyData, String useProxy) {
String requestUrl = url;
if (StringUtils.isNotBlank(params)) {
requestUrl = url + "?" + params;
}
String respData = null;
log.info("httpPost req is 【{}】", sendBodyData);
HttpRequest httpRequest = HttpRequest.post(requestUrl).timeout(socketTimeout).header("Content-Type", "application/json");
if ("Y".equalsIgnoreCase(useProxy)) {
log.info(String.format("使用代理"));
httpRequest.setProxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
}
if (StringUtils.isNotBlank(sendBodyData)) {
httpRequest.body(sendBodyData);
}
respData = httpRequest.execute().body();
log.info(String.format("HttpsUtil:httpPost | 請(qǐng)求信息:%s | 響應(yīng)信息: %s", httpRequest.getUrl(), respData));
return respData;
}
二、java net實(shí)現(xiàn)
1、java中http協(xié)議調(diào)用get請(qǐng)求文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-510383.html
package com.bjbn.app.tianfu.mq.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class GetMessage {
public static String getHttpRequestData(String data) {
// 首先抓取異常并處理
String returnString = "1";
try{
// 代碼實(shí)現(xiàn)以GET請(qǐng)求方式為主,POST跳過(guò)
/** 1 GET方式請(qǐng)求數(shù)據(jù) start*/
StringBuilder sb = new StringBuilder();
String urlP = "http://localhost:8500/main/dataAnalysis?data=";
sb.append(urlP);
data = URLEncoder.encode(data,"UTF-8");
sb.append(data);
// 1 創(chuàng)建URL對(duì)象,接收用戶傳遞訪問(wèn)地址對(duì)象鏈接
URL url = new URL(sb.toString());
// 2 打開(kāi)用戶傳遞URL參數(shù)地址
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
// 3 設(shè)置HTTP請(qǐng)求的一些參數(shù)信息
connect.setRequestMethod("GET"); // 參數(shù)必須大寫(xiě)
connect.connect();
// 4 獲取URL請(qǐng)求到的數(shù)據(jù),并創(chuàng)建數(shù)據(jù)流接收
InputStream isString = connect.getInputStream();
// 5 構(gòu)建一個(gè)字符流緩沖對(duì)象,承載URL讀取到的數(shù)據(jù)
BufferedReader isRead = new BufferedReader(new InputStreamReader(isString));
// 6 輸出打印獲取到的文件流
String str = "";
while ((str = isRead.readLine()) != null) {
str = new String(str.getBytes(),"UTF-8"); //解決中文亂碼問(wèn)題
// System.out.println("文件解析打?。?);
// System.out.println(str);
returnString = str;
}
// 7 關(guān)閉流
isString.close();
connect.disconnect();
// 8 JSON轉(zhuǎn)List對(duì)象
// do somthings
}catch(Exception e){
e.printStackTrace();
}
return returnString;
}
public static void main(String[] args) {
String data = "111111";
String httpRequestData = getHttpRequestData(data);
System.out.println(httpRequestData);
}
}
2、java中https協(xié)議調(diào)用get請(qǐng)求文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-510383.html
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class HttpUtils1 {
private static final String ENCODING = "UTF-8";
public static void main(String args[]) {
// get方式調(diào)用接口
String resultString = httpGet("https://xxxxx?systemCode=1&apiCode=1&accessCode=xxxx");
// 獲取接口信息
System.out.println(resultString);
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
/**
* Trust every server - dont check for any certificate
*/
private static void trustAllHosts() {
final String TAG = "trustAllHosts";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
public static String httpGet(String httpUrl) {
BufferedReader input = null;
StringBuilder sb = null;
URL url = null;
HttpURLConnection con = null;
try {
url = new URL(httpUrl);
try {
// trust all hosts
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection)url.openConnection();
if (url.getProtocol().toLowerCase().equals("https")) {
https.setHostnameVerifier(DO_NOT_VERIFY);
con = https;
} else {
con = (HttpURLConnection)url.openConnection();
}
input = new BufferedReader(new InputStreamReader(con.getInputStream()));
sb = new StringBuilder();
String s;
while ((s = input.readLine()) != null) {
sb.append(s).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} finally {
// close buffered
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}}
// disconnecting releases the resources held by a connection so they may be closed or reused
if (con != null) {
con.disconnect();
}
}
return sb == null ? null : sb.toString();
}
}
到了這里,關(guān)于java中使用hutool調(diào)用get請(qǐng)求,post請(qǐng)求的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!