網上面有很多,但是我們項目怎么也調不到結果,試了差不多很多案例,都是報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接口的話,可以復制以上四個類。運行最后兩個類。