- pom.xml中添加Commons-httpclient包
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
- Http请求工具类
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpClientUtil {
public static String doGet(String url, String charset) {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("请求出错:" + getMethod.getStatusLine());
}
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
} catch (HttpException e) {
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("发生网络异常!");
} finally {
getMethod.releaseConnection();
}
return response;
}
public static String doPost(String url, JSONObject jsonObject){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
postMethod.setRequestEntity(new StringRequestEntity(jsonObject.toString()));
String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
res = postMethod.getResponseBodyAsString();
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public static void main(String[] args) {
Map<String, String> params = new HashMap<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("webankAppId", FaceConfig.APP_ID);
jsonObject.put("name", "name");
jsonObject.put("orderNo", "orderNo");
jsonObject.put("idNo", "idCard");
jsonObject.put("userId", "userId");
jsonObject.put("version", "name");
jsonObject.put("sign", "sign");
String h5faceidResult = HttpClientUtil.doPost("https://miniprogram-kyc.tencentcloudapi.com/api/server/h5/geth5faceid", jsonObject);
System.out.println(h5faceidResult);
}
}