在做一些项目的时候,会调用一些成型的api,之后直接以接口进行连接,在Java程序里面,会出现调用外部接口的情况,以前做的时候,只使用过ajax来请求,在Java里面去请求外部接口,还是第一次做,其实在postman里面有这个代码可以参考,但是还是自己封装了一套属于自己的一套公共方法,用来记录一下。
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
public class HttpClientUtil {
@SuppressWarnings("resource")
public static String doGet(Map<String, String> map) {
HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
// Basic YXBpOlFBWldTWC0yMDE5MDRxYXp3c3g=
try {
httpClient = new SSLClient();
httpGet = new HttpGet(map.get("url"));
httpGet.addHeader("Content-Type", "application/json");
httpGet.addHeader("Authorization", map.get("userInfo"));
HttpResponse response = httpClient.execute(httpGet);
result = transformationHttpResponseToString(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
@SuppressWarnings("resource")
public static String doPost(Map<String, String> map,String data) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(map.get("url"));
httpPost.addHeader("Content-Type", "application/xml; charset=utf-8");
httpPost.addHeader("Authorization", map.get("userInfo"));
httpPost.setHeader("Content-Type","application/xml; charset=utf-8");
StringEntity se = new StringEntity(data, Charset.forName("UTF-8"));
se.setContentEncoding("UTF-8");
se.setContentType("application/xml");
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
result = transformationHttpResponseToString(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
@SuppressWarnings("resource")
public static String doDelete(Map<String, String> map) {
HttpClient httpClient = null;
HttpDelete httpDelete = null;
String result = null;
try {
httpClient = new SSLClient();
httpDelete = new HttpDelete(map.get("url"));
httpDelete.addHeader("Content-Type", "application/json");
httpDelete.addHeader("Authorization", map.get("userInfo"));
HttpResponse response = httpClient.execute(httpDelete);
result = transformationHttpResponseToString(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
@SuppressWarnings("resource")
public static String doPut(Map<String, String> map) {
HttpClient httpClient = null;
HttpPut httpPut = null;
String result = null;
try {
httpClient = new SSLClient();
httpPut = new HttpPut(map.get("url"));
httpPut.addHeader("Content-Type", "application/xml");
httpPut.addHeader("Authorization", map.get("userInfo"));
httpPut.setHeader("Content-Type", "application/xml");
StringEntity se = new StringEntity(map.get("data"), Charset.forName("UTF-8"));
se.setContentEncoding("UTF-8");
se.setContentType("application/xml");
httpPut.setEntity(se);
HttpResponse response = httpClient.execute(httpPut);
result = transformationHttpResponseToString(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
private static String transformationHttpResponseToString(HttpResponse response) {
String result = "";
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
try {
result = EntityUtils.toString(resEntity, "utf-8");
StatusLine statusLine = response.getStatusLine();
int code = statusLine.getStatusCode();
//判断了code 码为200则是请求成功,其他的时候,都是错误数据的展示,因为错误数据返回的是json
if(code==200){
result = XmlOrJsonOrStringUtil.xmlToJson(result).toString();
if(StringUtils.isBlank(result)||StringUtils.equals(result,"{}")||StringUtils.equals(result,"[]")){
JSONObject json = new JSONObject();
json.put("code",200);
result = JSONObject.toJSONString(json);
}
}else if(code==201){
JSONObject json = new JSONObject();
Header[] headers = response.getHeaders("Location");
json.put("code","201");
json.put("header",headers[0].getValue());
result = JSONObject.toJSONString(json);
}else{
JSONObject json = new JSONObject();
json.put("code","400");
result = JSONObject.toJSONString(json);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
这个是上面的代码用到的一个工具类,之后自己写的,这个是逃避ssl证书。
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}