Several ways to access remote interface in Java

1. Get native Java API

package com.util;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * <pre>
 * Function: httpUrlConnection access remote interface tool
 * Date: March 17, 2015 11:19:21 AM
 * </pre>
 */
public class HttpUrlConnectionUtil {

    /**
     * <pre>
     * Method body description: initiate a request to the remote interface and return a string type result
     * @param url interface address
     * @param requestMethod request method
     * @param params Key points for passing parameters: parameter values ​​need to be transcoded with Base64
     * @return String return result
     * </pre>
     */
    public static String httpRequestToString(String url, String requestMethod,
            Map<String, String> params){

        String result = null;
        try {
            InputStream is = httpRequestToStream(url, requestMethod, params);
            byte[] b = new byte[is.available()];
            is.read(b);
            result = new String(b);
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return result;
    }

    /**
     * <pre>
     * Method body description: initiate a request to the remote interface and return the result of byte stream type
     * Author: itar
     * Date: March 17, 2015 11:20:25 AM
     * @param url interface address
     * @param requestMethod request method
     * @param params Key points for passing parameters: parameter values ​​need to be transcoded with Base64
     * @return InputStream returns the result
     * </pre>
     */
    public static InputStream httpRequestToStream(String url, String requestMethod,
            Map<String, String> params){

        InputStream is = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            //Splicing the parameter set into a specific format, such as name=zhangsan&age=24
            for(String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){
                parameters = parameters.substring(0, parameters.length()-1);
            }

            //Whether the request method is get
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            //Whether the request method is post
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            if(isGet){
                url += "?"+ parameters;
            }

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            //The parameter type of the request (when using the restlet framework, in order to be compatible with the framework, the Content-Type must be set to "" empty)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //Set the connection timeout
            conn.setConnectTimeout(50000);  
            //Set the timeout for reading the returned content
            conn.setReadTimeout(50000);
            //Set the output to the HttpURLConnection object, because the post method puts the request parameters in the http body, so it needs to be set to true, the default is false
            if(isPost){
                conn.setDoOutput(true);
            }
            //Set to read from the HttpURLConnection object, the default is true
            conn.setDoInput(true);
            //Set whether to use the cache, the post method cannot use the cache
            if(isPost){
                conn.setUseCaches(false);
            }
            //Set the request method, the default is GET
            conn.setRequestMethod(requestMethod);

            //The post method needs to output the passed parameters to the conn object
            if(isPost){
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(parameters);
                dos.flush();
                dos.close();
            }

            //Read the response message from the HttpURLConnection object
            //The request is officially initiated when the statement is executed
            is = conn.getInputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        } catch (MalformedURLException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return is;
    }
}

2. Use httpClient to access and obtain

package com.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
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.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;


/**
 * <pre>
 * Function: httpClient access remote interface tool class
 * Date: March 17, 2015 11:19:21 AM
 * </pre>
 */
@SuppressWarnings("deprecation")
public class HttpClientUtil {

    /**
     * <pre>
     * Method body description: initiate a request to the remote interface and return a string type result
     * @param url interface address
     * @param requestMethod request type
     * @param params pass parameters
     * @return String return result
     * </pre>
     */
    public static String httpRequestToString(String url, String requestMethod,
            Map<String, String> params, String ...auth){
        //The interface returns the result
        String methodResult = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            //Splicing the parameter set into a specific format, such as name=zhangsan&age=24
            for(String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){
                parameters = parameters.substring(0, parameters.length()-1);
            }
            //Whether it is a GET request
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            boolean isPut = "put".equalsIgnoreCase(requestMethod);
            boolean isDelete = "delete".equalsIgnoreCase(requestMethod);

            //Create HttpClient connection object
            DefaultHttpClient client = new DefaultHttpClient();
            HttpRequestBase method = null;
            if(isGet){
                url += "?" + parameters;
                method = new HttpGet(url);
            }else if(isPost){
                method = new HttpPost(url);
                HttpPost postMethod = (HttpPost) method;
                StringEntity entity = new StringEntity(parameters);
                postMethod.setEntity(entity);
            }else if(isPut){
                method = new HttpPut(url);
                HttpPut putMethod = (HttpPut) method;
                StringEntity entity = new StringEntity(parameters);
                putMethod.setEntity(entity);
            }else if(isDelete){
                url += "?" + parameters;
                method = new HttpDelete(url);
            }
            method.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
            //Set the parameter content type
            method.addHeader("Content-Type","application/x-www-form-urlencoded");
            //httpClient local context
            HttpClientContext context = null;
            if(!(auth==null || auth.length==0)){
                String username = auth[0];
                String password = auth[1];
                UsernamePasswordCredentials credt = new UsernamePasswordCredentials(username,password);
                //credential provider
                CredentialsProvider provider = new BasicCredentialsProvider();
                // match scope of credentials
                provider.setCredentials(AuthScope.ANY, credt);
                context = HttpClientContext.create();
                context.setCredentialsProvider(provider);
            }
            //Access the interface, return the status code
            HttpResponse response = client.execute(method, context);
            //Return status code 200, the access interface is successful
            if(response.getStatusLine().getStatusCode()==200){
                methodResult = EntityUtils.toString(response.getEntity());
            }
            client.close();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }catch (IOException e) {
            e.printStackTrace ();
        }
        return methodResult;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325984185&siteId=291194637