网上面有很多,但是我们项目怎么也调不到结果,试了差不多很多案例,都是报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接口的话,可以复制以上四个类。运行最后两个类。

调用http接口的工具类的更多相关文章

  1. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  2. 双列集合Map接口 & Collections工具类

    HashMap 常用方法 遍历方式 iterator迭代器  ITIT HashTable 继承字典 Hashtable--Properties 文件读写 总结 Collections工具类

  3. C# 调用API接口处理公共类 自带JSON实体互转类

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...

  4. Java使用OkHttps工具类调用外部接口

    前言 现在公司业务已止不是传统的增删改查等简单的业务处理操作,而是对数据各种联调三方接口与其他系统进行交互等,那么就需要我们在后台java中进行外部接口的调用,本文采用OkHttps工具类对接微信接口 ...

  5. java 调用webservice接口wsdl,推荐使用wsdl2java,放弃wsimport

    网上说wsimport是jdk1.6后自带的客户端生成调用webservice接口的工具,其实我挺喜欢原生的东西,毕竟自家的东西用着应该最顺手啊,但往往让人惊艳的是那些集成工具. 本机jdk1.8.1 ...

  6. PHP常用工具类积累

    第一 请求第三方接口的工具类 例如,封装了get和post请求方法的工具类,代码如下: <?php class HttpClient{ /** * HttpClient * @param arr ...

  7. commons工具类

    转自:https://blog.csdn.net/leaderway/article/details/52387925 1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不 ...

  8. Properties-转换流-打印流-序列化和反序列化-Commons-IO工具类

    一.Properties 类(java.util)     概述:Properties 是一个双列集合;Properties 属于map的特殊的孙子类;Properties 类没有泛型,propert ...

  9. laravel封装返回json信息工具类

    1.工具类可以一次写入多方多方调用,很大程度的节约开发时间得到想要的信息 这里演示一个json接口的工具类(文件定义在App\Http\Controllers\Tools)中 <?php /** ...

随机推荐

  1. jsp tutorial

    http://blog.csdn.net/JavaEETeacher/article/details/1932447

  2. epoll浅析以及nio中的Selector

    出处: https://my.oschina.net/hosee/blog/730598 首先介绍下epoll的基本原理,网上有很多版本,这里选择一个个人觉得相对清晰的讲解(详情见reference) ...

  3. python多线程的两种写法

    1.一般多线程 import threading def func(arg): # 获取当前执行该函数的线程的对象 t = threading.current_thread() # 根据当前线程对象获 ...

  4. 安全技能树简版 正式发布——BY 余弦(知道创宇)

    之前留意到知道创宇发布的<知道创宇研发技能表>,对自己有很大的启发,最近听说知道创宇的余弦大神创业了(题外话),还发布了<安全技能树简版V1>,仔细研读之后总体感觉不那么复杂了 ...

  5. Spark SQL原理和实现--王家林老师

  6. c++ ScopeExitGuard

    说到Native Languages就不得不说资源管理,因为资源管理向来都是Native Languages的一个大问题,其中内存管理又是资源当中的一个大问题,由于堆内存需要手动分配和释放,所以必须确 ...

  7. python并发编程之IO模型(Day38)

    一.IO模型介绍 为了更好的学习IO模型,可以先看同步,异步,阻塞,非阻塞 http://www.cnblogs.com/linhaifeng/articles/7430066.html#_label ...

  8. 把RedisWatcher安装为windows服务

    安装完成后, 到安装目录下修改watcher.conf.注意,任何路径都不可包含空格,中文,特殊字符,且全部使用绝对路径配置文件中文注释exepath --> redis-server.exe的 ...

  9. LeetCode:每日温度【739】

    LeetCode:每日温度[739] 题目描述 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数.如果之后都不会升高,请输入 0 来代替. 例如,给定一个列 ...

  10. PAT 天梯赛 L1-013. 计算阶乘和 【水】

    题目链接 https://www.patest.cn/contests/gplt/L1-013 AC代码 #include <iostream> #include <cstdio&g ...