调用http接口的工具类
网上面有很多,但是我们项目怎么也调不到结果,试了差不多很多案例,都是报connection reset 后来,我发现是有一个验证,需要跳过验证。然后才能调接口。所以找了一个忽略https的方法。进行改造。先调了一个token接口,传入用户名和密码,发现果然有参数返回,但是再调其他接口时,却又调不到了。这时,我用set -header调整了顺序,和大小写,成功读取了post请求的接口,而后顺利的改写了get方法。试验成功。最后又delete 和put没有调到参数,DElete是需要继承一个类,不然不能set参数进去,只能进行无参数操作。不过还是不行,我一度以为改写错误,最后debugger发现。原来是华为方,小哥linux部署有问题,200,和400的状态码搞混淆了。我用状态码进行判断了,都被阻挡了。所以最终我取消了状态码判断。他也取消了状态码。最终代码如下
HttpUtils工具类。
package com.nariwebsocket;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpsUtils {
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
static {
try {
builder = new SSLContextBuilder();
// ȫ������ ������ݼ�
builder.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTP, new PlainConnectionSocketFactory())
.register(HTTPS, sslsf)
.build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);//max connection
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* httpClient post����
* @param url ����url
* @param header ͷ����Ϣ
* @param entity ����ʵ�� json/xml�ύ����
* @return ����Ϊ�� ��Ҫ����
* @throws Exception
*
*/
public static String post(String url, Map<String, String> header, HttpEntity entity) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
// ����ͷ��Ϣ
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// �����������
// ����ʵ�� ���ȼ���
if (entity != null) {
httpPost.setEntity(entity);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
/* int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} else {readHttpResponse(httpResponse);
}*/
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
} catch (Exception e) {throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
public static String get(String url, Map<String, String> header) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpGet httpget = new HttpGet(url);
// ����ͷ��Ϣ
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpget.addHeader(entry.getKey(), entry.getValue());
}
}
// �����������
HttpResponse httpResponse = httpClient.execute(httpget);
/*int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} else {readHttpResponse(httpResponse);
}*/
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} catch (Exception e) {throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
/**
* httpClient delete����
* @param url ����url
* @param header ͷ����Ϣ
* @param entity ����ʵ�� json/xml�ύ����
* @return ����Ϊ�� ��Ҫ����
* @throws Exception
*
*/
public static String delete(String url, Map<String, String> header, HttpEntity entity) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
//HttpDelete httpdelete = new HttpDelete(url);
HttpDeleteWithBody httpdelete =new HttpDeleteWithBody(url);
//DeleteMethod deleteMethod=new DeleteMethod(url);
// ����ͷ��Ϣ
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpdelete.setHeader(entry.getKey(), entry.getValue());
}
}
//httpdelete.setHeader("X-Requested-With", "XMLHttpRequest");
// �����������
// ����ʵ�� ���ȼ���
if (entity != null) {
httpdelete.setEntity(entity);
}
//ttpdelete.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
HttpResponse httpResponse = httpClient.execute(httpdelete);
/* int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity,"UTF-8");
} else {readHttpResponse(httpResponse);
}*/
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity,"UTF-8");
} catch (Exception e) {throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
/**
* httpClient post����
* @param url ����url
* @param header ͷ����Ϣ
* @param entity ����ʵ�� json/xml�ύ����
* @return ����Ϊ�� ��Ҫ����
* @throws Exception
*
*/
public static String put(String url, Map<String, String> header, HttpEntity entity) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPut httpPut = new HttpPut(url);
// ����ͷ��Ϣ
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPut.addHeader(entry.getKey(), entry.getValue());
}
}
// �����������
// ����ʵ�� ���ȼ���
if (entity != null) {
httpPut.setEntity(entity);
}
HttpResponse httpResponse = httpClient.execute(httpPut);
/*int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
} else {readHttpResponse(httpResponse);
}*/
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
} catch (Exception e) {throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
public static CloseableHttpClient getHttpClient() throws Exception {
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.build();
return httpClient;
}
public static String readHttpResponse(HttpResponse httpResponse)
throws ParseException, IOException {
StringBuilder builder = new StringBuilder();
// ��ȡ��Ӧ��Ϣʵ��
HttpEntity entity = httpResponse.getEntity();
// ��Ӧ״̬
builder.append("status:" + httpResponse.getStatusLine());
builder.append("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
builder.append("\t" + iterator.next());
}
// �ж���Ӧʵ���Ƿ�Ϊ��
if (entity != null) {
String responseString = EntityUtils.toString(entity);
builder.append("response length:" + responseString.length());
builder.append("response content:" + responseString.replace("\r\n", ""));
}
return builder.toString();
}
}
delete 继承类,跟HttpUtlis类放在一起(上面的那个类):
package com.nariwebsocket;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() { return METHOD_NAME; }
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() { super(); }
}
最后是两个测试类:
Token接口测试类:
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.http.entity.StringEntity;
import com.nariwebsocket.HttpsUtils;
public class test {
private static final String DEVICERUNINFO_URL = "https://10.10.1.14:18008/controller/v2/tokens";
public static void main(String[] args) throws Exception {
Map<String, String> header = new HashMap<String, String>();
Map<String, Object> param = new HashMap<String, Object>();
Map<String, String> p = new HashMap<String, String>();
header.put("Accept", "application/json");
header.put("Content-Type", "application/json");
List<String> containerNames=new ArrayList<String>();
containerNames.add("wqwqe");
param.put("esn","1111111");
param.put("containerNames",containerNames);
p.put("userName", "north@huawei.com");
p.put("password", "Huawei12#$");
String string = JSONObject.fromObject(p).toString();
StringEntity stringEntity = new StringEntity(string);
String post = HttpsUtils.post(DEVICERUNINFO_URL, header,stringEntity);
System.out.println(post);
}
}
得到的token_id放在请求头中再访问其他接口:
package test;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import com.nariwebsocket.HttpsUtils;
public class Test2 {
private static final String TOKEN ="D8C6230E48734D88:23D7A8E0F71E47AAA8CB116FEB922E437C80185CC4874515B5873DF3586031E6";
private static final String POST_URL ="https://10.10.1.14:18008/controller/iot/sg/v1/devices";
private static final String GET_URL = "https://10.10.1.14:18008/controller/iot/sg/v1/devices/clock/21500101763GE6001234";
private static final String PUT_URL = "https://10.10.1.14:18008/controller/iot/sg/v1/devices/21500101763GE6001234";
private static final String DEL_URL = "https://10.10.1.14:18008/controller/iot/sg/v1/devices?esn=11";
public static void main(String[] args) throws Exception {
postMethod();
getMethod();
putMethod();
deleteMethod();
}
public static void postMethod() throws UnsupportedEncodingException,
Exception {
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json");
header.put("Accept", "application/json");
header.put("x-Access-Token",TOKEN);
String string = "{\"devices\":[{\"esn\":\"21500101763GE6001234\"},{\"esn\":\"21500101763GE6001264\"}]}";
StringEntity stringEntity = new StringEntity(string);
String postStr = HttpsUtils.post(POST_URL, header, stringEntity);
System.out.println("post:"+postStr);
}
public static void getMethod() throws Exception {
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json");
header.put("Accept", "application/json");
header.put("x-Access-Token",TOKEN);
String getStr = HttpsUtils.get(GET_URL, header);
System.out.println("get:"+getStr);
}
public static void putMethod() throws UnsupportedEncodingException,Exception {
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json");
header.put("Accept", "application/json");
header.put("x-Access-Token",TOKEN);
String string = "{\"name\":\"device1\",\"description\":\"dd\",\"gisLon\":\"2.5\",\"gisLat\":\"3.9\"}";
StringEntity stringEntity = new StringEntity(string);
String putStr = HttpsUtils.put(PUT_URL, header, stringEntity);
System.out.println("put:"+putStr);
}
public static void deleteMethod() throws Exception {
Map<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json");
header.put("Accept", "application/json");
header.put("x-Access-Token",TOKEN);
String string = "{\"devices\":[{\"esn\":\"21500101763GE6001234\"},{\"esn\":\"21500101763GE6001264\"}]}";
StringEntity stringEntity = new StringEntity(string,Consts.UTF_8);
String delStr = HttpsUtils.delete(DEL_URL, header, stringEntity);
System.out.println("del:"+delStr);
}
}
post,get ,put,delete都有,如果你也有token_id权限访问restful风格的http接口的话,可以复制以上四个类。运行最后两个类。