基于HttpClient调用Open API
本节介绍如何搭建一个调用Open API接口的开发应用。
开发环境搭建
本节展示如何搭建基于HttpClient的项目,实现调用查询网管系统信息的Open API接口。
工程结构说明
│─lib │ └─com.springsource.org.apache.commons.codec-1.3.0.jar │ └─com.springsource.org.apache.commons.lang-2.4.0.jar │ └─commons-beanutils-1.8.0.jar │ └─commons-collections-3.2.1.jar │ └─commons-logging-1.1.1.jar │ └─ezmorph-1.0.6.jar │ └─httpclient-4.2.2.jar │ └─httpcore-4.2.2.jar │ └─json-lib-2.4-jdk15.jar │─src │ └─com │ └─huawei │ └─nms │ └─openapi │ └─demo │ └─global │ └─GlobalVar.java │ └─NewHttpsAccess.java │ └─NewRosSecurity.java │ └─sm │ └─Login.java │ └─QuerySystemInfo.java
- *.java文件是本应用的源代码,编码格式为UTF-8。Login.java用于获取openid;NewHttpsAccess.java文件用于建立连接;GlobalVar.java主要用于保存OpenAPI的服务端ip、端口、openid、登录的用户名以及密码;NewRosSecurity.java用于其他业务代码构造带openid的请求头部;QuerySystemInfo.java为调用业务接口的示例。
- *.jar文件是本应用依赖的jar包。为了确保编译正确,请按照上述列表获取对应版本的jar包。
- 建议使用JRE 1.8或以上版本。
可以参考图3-7在Eclipse开发环境中创建本应用的工程。
依赖开源软件包说明
序号 |
开源软件包名称 |
版本 |
下载地址 |
---|---|---|---|
1 |
com.springsource.org.apache.commons.codec |
1.3.0 |
http://commons.apache.org/proper/commons-codec/download_codec.cgi |
2 |
com.springsource.org.apache.commons.lang |
2.4.0 |
http://commons.apache.org/proper/commons-lang/download_lang.cgi |
3 |
commons-beanutils |
1.8.0 |
http://commons.apache.org/proper/commons-beanutils/index.html |
4 |
commons-collections |
3.2.1 |
|
5 |
commons-logging |
1.1.1 |
|
6 |
ezmorph |
1.0.6 |
|
7 |
httpclient |
4.2.2 |
|
8 |
httpcore |
4.2.2 |
|
9 |
json-lib |
2.4 |
基于openid认证开发应用
- 登录并获取openid。
// Login.java package com.huawei.nms.openapi.demo.sm; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.message.BasicNameValuePair; import com.huawei.nms.openapi.demo.global.GlobalVar; import com.huawei.nms.openapi.demo.global.NewHttpsAccess; import net.sf.json.JSONObject; /* * Log in Example */ public class Login { public static void main(String[] args) throws Exception { login(); } public static void login() throws Exception { //set the URL and method final String openidURL = "/rest/openapi/sm/session"; final String method = "PUT"; //set parameters final List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("userid", GlobalVar.GLOBAL_USERNAME)); parameters.add(new BasicNameValuePair("value", GlobalVar.GLOBAL_USERVALUE)); parameters.add(new BasicNameValuePair("ipaddr", GlobalVar.GLOBAL_USERIP)); //send the request final HttpResponse response = NewHttpsAccess.access(GlobalVar.GLOBAL_IP, GlobalVar.GLOBAL_PORT, openidURL, method, null, parameters); //get the result final String ret = NewHttpsAccess.getResult(response); System.out.println(ret); //resolve the result and get the openid final JSONObject jObject = JSONObject.fromObject(ret); if (null == jObject) { System.out.println("Login failed."); return; } if ("0".equals(String.valueOf(jObject.get("code")))) { final String openid = String.valueOf(jObject.get("data")); GlobalVar.globalOpenid = openid; } } }
- 调用接口。
// QuerySystemInfo.java package com.huawei.nms.openapi.demo.sm; import org.apache.http.HttpResponse; import org.apache.http.message.BasicNameValuePair; import com.huawei.nms.openapi.demo.global.GlobalVar; import com.huawei.nms.openapi.demo.global.NewHttpsAccess; import com.huawei.nms.openapi.demo.global.NewRosSecurity; /** * Query System Information */ public class QuerySystemInfo { /** * Open API URI */ private static final String QUERY_SYSTEM_INFO_URI = "/rest/openapi/systemInfo"; public static void main(final String[] args) throws Exception { Login.login(); querySystemInfo(); } public static void querySystemInfo() throws Exception { // set the URL and method final String openidURI = QUERY_SYSTEM_INFO_URI; final String method = "GET"; // set headers final BasicNameValuePair[] headers = NewRosSecurity.getRosHttpHeader(openidURI, method); // set parameters final BasicNameValuePair[] parameters = null; // send the request final HttpResponse response = NewHttpsAccess.access(GlobalVar.GLOBAL_IP, GlobalVar.GLOBAL_PORT, openidURI, method, headers, parameters); // get the result final String body = NewHttpsAccess.getResult(response); System.out.println(body); } }
GlobalVar定义
GlobalVar.java文件中定义了全部的全局变更。
具体变量请参考以下代码。
package com.huawei.nms.openapi.demo.global; /** * globalVar * */ public class GlobalVar { /** * server IP */ public static final String GLOBAL_IP = "10.137.63.100"; /** * server port for HTTPS */ public static final int GLOBAL_PORT = 32102; /** * user id */ public static final String GLOBAL_USERNAME = "openapi"; /** * user password */ public static final String GLOBAL_USERVALUE = "Huawei123"; /** * user IP */ public static final String GLOBAL_USERIP = "10.66.66.58"; /** * openid */ public static String globalOpenid = ""; }
NewHttpsAccess定义
NewHttpsAccess.java文件用于建立服务端与客户端之间的连接。
具体方法请参考以下代码。
package com.huawei.nms.openapi.demo.global; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; 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.client.methods.HttpUriRequest; 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; import org.apache.http.impl.conn.BasicClientConnectionManager; import org.apache.http.message.BasicNameValuePair; public class NewHttpsAccess { /** * set headers and parameters */ public static HttpResponse access(final String ip, final int port, final String url, final String method, final BasicNameValuePair[] headers, final BasicNameValuePair[] parameters) throws Exception { List<BasicNameValuePair> headers2 = null; List<BasicNameValuePair> parameters2 = null; if (null != headers) { headers2 = new ArrayList<BasicNameValuePair>(); for (final BasicNameValuePair e : headers) { headers2.add(e); } } if (null != parameters) { parameters2 = new ArrayList<BasicNameValuePair>(); for (final BasicNameValuePair e : parameters) { parameters2.add(e); } } return access(ip, port, url, method, headers2, parameters2); } /** * connect to the host by HttpClient */ public static HttpResponse access(final String ip, final int port, String url, final String method, final List<BasicNameValuePair> headers, final List<BasicNameValuePair> parameters) throws Exception { //create a connection manager final X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(final X509Certificate[] xcs, final String string) { } public void checkServerTrusted(final X509Certificate[] xcs, final String string) { } public X509Certificate[] getAcceptedIssuers() { return null; } }; //create a SSL connection final SSLContext sslcontext = SSLContext.getInstance("TLSv1.2"); sslcontext.init(null, new TrustManager[] {tm}, null); final SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", port, socketFactory)); //create a HttpClient to connect to the target host final HttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry)); //set the URL url = "https://" + ip + ":" + port + url; System.out.println(url); //set the method HttpUriRequest httpRequest = null; if ("PUT".equalsIgnoreCase(method)) { final HttpPut httpPut = new HttpPut(url); httpRequest = httpPut; if (null != parameters) { try { final UrlEncodedFormEntity tmp = new UrlEncodedFormEntity(parameters, "UTF-8"); httpPut.setEntity(tmp); } catch (final UnsupportedEncodingException e1) { e1.printStackTrace(); } } } else if ("POST".equalsIgnoreCase(method)) { final HttpPost httpPost = new HttpPost(url); httpRequest = httpPost; if (null != parameters) { try { final UrlEncodedFormEntity tmp = new UrlEncodedFormEntity(parameters, "UTF-8"); httpPost.setEntity(tmp); } catch (final UnsupportedEncodingException e1) { e1.printStackTrace(); } } } else if ("GET".equalsIgnoreCase(method)) { if (null != parameters) { url += "?"; boolean init = false; for (final BasicNameValuePair e : parameters) { if (!init) { url += URLEncoder.encode(e.getName(), "UTF-8") + "=" + URLEncoder.encode(e.getValue(), "UTF-8"); init = true; } else { url += "&" + URLEncoder.encode(e.getName(), "UTF-8") + "=" + URLEncoder.encode(e.getValue(), "UTF-8"); } } } final HttpGet httpGet = new HttpGet(url); httpRequest = httpGet; } else if ("DELETE".equalsIgnoreCase(method)) { if (null != parameters) { url += "?"; boolean init = false; for (final BasicNameValuePair e : parameters) { if (!init) { url += URLEncoder.encode(e.getName(), "UTF-8") + "=" + URLEncoder.encode(e.getValue(), "UTF-8"); init = true; } else { url += "&" + URLEncoder.encode(e.getName(), "UTF-8") + "=" + URLEncoder.encode(e.getValue(), "UTF-8"); } } } final HttpDelete httpDelete = new HttpDelete(url); httpRequest = httpDelete; } else { return null; } //set headers if (null != headers) { for (final BasicNameValuePair header : headers) { httpRequest.setHeader(header.getName(), header.getValue()); } } //send the request final HttpResponse response = httpClient.execute(httpRequest); return response; } /** * get the result */ public static String getResult(final HttpResponse response) throws IllegalStateException, IOException { final InputStream is = response.getEntity().getContent(); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); String ret = ""; String line = ""; while ((line = br.readLine()) != null) { if (!ret.isEmpty()) { ret += "\n"; } ret += line; } return ret; } }
NewRosSecurity定义
NewRosSecurity.java用于构造带openid的请求头部。
具体方法请参考以下代码。
package com.huawei.nms.openapi.demo.global; import org.apache.http.message.BasicNameValuePair; public class NewRosSecurity { public static long nounce = 0; private static BasicNameValuePair[] getRosOpenidHeader() { final BasicNameValuePair[] headers = { new BasicNameValuePair("openid", GlobalVar.globalOpenid)}; return headers; } public static BasicNameValuePair[] getRosHttpHeader(final String url, final String method) { return getRosOpenidHeader(); } }