No relevant resource is found in the selected language.

This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies. Read our privacy policy>Search

Reminder

To have a better experience, please upgrade your IE browser.

upgrade

eSight V300R010C00SPC200, 300, and 500 Self-Service Integration Guide 10

Rate and give feedback:
Huawei uses machine translation combined with human proofreading to translate this document to different languages in order to help you better understand the content of this document. Note: Even the most advanced machine translation cannot match the quality of professional translators. Huawei shall not bear any responsibility for translation accuracy and it is recommended that you refer to the English document (a link for which has been provided).
Invoking Open APIs Based on the HttpClient

Invoking Open APIs Based on the HttpClient

This section describes how to set up an application that can invoke Open APIs.

Setting up a Development Environment

This section describes how to set up a project based on the HttpClient to invoke the Open API for querying eSight information.

Project structure description

The structure of this application package is as follows:
│─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
  • The *.java files are the source code of this application. The encoding format is UTF-8. The Login.java file is used to obtain openid. The NewHttpsAccess.java file is used to establish a connection. The GlobalVar.java file stores the IP address, port number, openid, login user name, and password of the Open API server. The NewRosSecurity.java file is used by other service codes to construct request headers with openid. The QuerySystemInfo.java file provides an example of invoking a service interface.
  • The *.jar files are JAR packages that the application depends on. To ensure correct compilation, obtain the JAR packages of the required version based on the preceding list.
  • JRE 1.8 or later is recommended.

For details about how to create a project in the Eclipse development environment, see Figure 3-7.

Figure 3-7 Project structure

Dependent Open-Source Software Packages

No.

Open-Source Software Package

Version

How to Obtain

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

http://commons.apache.org/proper/commons-collections/

5

commons-logging

1.1.1

http://commons.apache.org/proper/commons-logging/

6

ezmorph

1.0.6

http://ezmorph.sourceforge.net/

7

httpclient

4.2.2

http://hc.apache.org/

8

httpcore

4.2.2

http://hc.apache.org/

9

json-lib

2.4

http://json-lib.sourceforge.net/

Developing an Application based on openid Authentication

  • The following code does not validate the server certificate. It is for reference only. During development by a third party, it is recommended that the certificate be validated. Otherwise, security risks exist.
  • Ensure that the protocol version used by the client is the same as that used by the server. Otherwise, the interface cannot be invoked. For details about how to configure the protocol version on the server, see Modifying the Configuration File.
  1. Log in to eSight and obtain the value of 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;
            }
        }
    }

  2. Invoke the interface.

    // 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);
        }
    
    }

Defining GlobalVar

The GlobalVar.java file defines all global variables.

For the variables, see the following codes.

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 = "";
}

Defining NewHttpsAccess

The NewHttpsAccess.java file is used to set up the connection between the server and client.

For details about the methods, see the following codes.

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;
    }
}

Defining NewRosSecurity

The NewRosSecurity.java file is used to construct a request header with openid.

For details about the methods, see the following codes.

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();
    }
}
Translation
Download
Updated: 2019-10-30

Document ID: EDOC1100044386

Views: 17108

Downloads: 84

Average rating:
This Document Applies to these Products
Related Version
Related Documents
Share
Previous Next