httpclient analog post, get request

Json form data package.

Sending a request tools:

package com.chinecredit.eccis.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * http访问方法实现
 * @author HYJ
 * / 
Public  class HttpRequestUtils {
     Private  static Logger = Logger of LoggerFactory 
            .getLogger (HttpRequestUtils. Class ); // logging 

    / ** 
     * Submit the GET 
     * @return 
     * / 
    public  static String the doGet (String URL) { 
        String strResult = "" ;
         // Create a default client instance 
        CloseableHttpClient client = HttpClients.createDefault ();
         the try {
             // 2. Create a httpget objects 
            HttpGet HttpGet = new newHttpGet (URL); 
            System.out.println ( "Executing GET Request" + httpGet.getURI ()); 

            // 3. performing a GET request and get a response object 
            CloseableHttpResponse RESP = client.execute (HttpGet);
             the try {
                 // . 6 Print length and response content in response 
                IF (resp.getStatusLine () getStatusCode () ==. HttpStatus.SC_OK) {
                     // 4. fetch response thereof 
                    the HttpEntity Entity = resp.getEntity (); 
                    System.out.println ( "the response content = length " 
                            + entity.getContentLength ()); 
                    System.out.println ("------" ); 
                    strResult = EntityUtils.toString (resp.getEntity ()); 
                } 
            } the finally {
                 // whether successful or not the request should be closed RESP 
                resp.close (); 
            } 
        } the catch (E ClientProtocolException ) { 
            logger.error ( "GET request failed:" , E);
             // e.printStackTrace (); 
        } the catch (a ParseException E) { 
            logger.error ( "GET request to resolve an error:" , E);
             // E. printStackTrace (); 
        } the catch(IOException E) { 
            logger.error ( "IO error GET request:" , E);
             // e.printStackTrace (); 
        } the finally {
             // 8. The final To close the connection, the release of resources 
            the try { 
                client.close (); 
            } the catch (Exception E) { 
                logger.error ( "complete GET request to close the connection error:" , E);
                 // e.printStackTrace (); 
            } 
        } 
        return strResult; 
    } 

   
    / ** 
     * POST JSON parametrically submitted 
     * @param url 
     * @paramthe params 
     * @return 
     * / 
    public  static String the doPost (String URL, the JSONObject the params) { 
        String strResult = "" ;
         // 1. get the default client instance 
        CloseableHttpClient client = HttpClients.createDefault ();
         // 2. Create instance httppost 
        HttpPost = HttpPost new new HttpPost (URL); 
        httpPost.addHeader ( "the Content-the Type", "file application / JSON; charset = UTF-. 8"); // add request header 
        the try { 
            httpPost.setEntity ( new new StringEntity (params.toJSONString () , "UTF-. 8" ));
            CloseableHttpResponse resp = client.execute(httpPost);
            try {
                // 7. 获取响应entity
                HttpEntity respEntity = resp.getEntity();
                strResult = EntityUtils.toString(respEntity, "UTF-8");
            } finally {
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }

   /**
     * json参数方式PUT提交
     * @param url
     * @param params
     * @return
     */
    public static String httpPut(String url) {
        String strResult = "";
        //1. Obtain the default client instance 
        CloseableHttpClient client = HttpClients.createDefault ();
         // 2. Create httppost instance 
        HTTP PUT HTTP PUT = new new HTTP PUT (URL); 
        httpPut.addHeader ( "the Content-the Type", "file application / JSON; charset = UTF -8 "); // add header request {the try 
            CloseableHttpResponse RESP = client.execute (HTTP PUT);
             the try {
                 // 7. The fetch response Entity 
                the HttpEntity respEntity = resp.getEntity (); 
                strResult = EntityUtils.toString (respEntity," UTF -8 " ); 
            } the finally {
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }
    
}

Encapsulated data specific method:

// get request
public
void String accessToken () { String param = "for appId = 4438770464 & Secret = 50988fde289384edd35588af67bfc8fb & grantType = client_credentials" ; String jsonStr = HttpGet ( "?" URI + "/ V1 / OAuth2 / the access_token" + + param); // get request path splicing } // when requested parameters are the same may be added when the level parameters directly, as follows: post request
public static void createByThirdPartyUserId (thirdPartyUserId String, String name, String idtype, idNumber String, String Mobile, String accessToken) { the JSONObject jsonParam = new new the JSONObject (); jsonParam.put ( "thirdPartyUserId", ThirdPartyUserId); jsonParam.put ( "name" , name); jsonParam.put ( "idtype" , idtype); jsonParam.put ( "idNumber" , idNumber); jsonParam.put ( "Mobile" , Mobile); String jsonStr HttpPost = (URI + "/ V1 / Accounts / createByThirdPartyUserId" , jsonParam); } // parameter when the request is json nested form, need to be set and then transformed entity classes: post request
public static void signflows (SignflowsVO signflowsVO ) { the JSONObject JSON = (the JSONObject) JSON.toJSON (signflowsVO); // JSON format data into String jsonStr= httpPost(uri + "/v1/signflows", json); }

Json request parameters are written in the form of a nested entity class, where only a simple example:

public  class SignflowsVO { 

    Private  Boolean AutoArchive; 
    
    Private String businessScene; 
    
    Private the ConfigInfo ConfigInfo; 
        
       //   GET, SET method omits 
} 


Package com.example.pojo.e; 

public  class PlatformSignVO { 
    
    Private Signfields signfields; 

         //   GET, SET method omits   
} 


/ / more than two classes is constructed of the following parameter types json format, if the type comprising an array Baidu 
{
     "AutoArchive": to false ,
     "businessScene": "contract name" ,
     "ConfigInfo" : {
         "noticeType": " 1,2 " 
    } 
}

 

Guess you like

Origin www.cnblogs.com/H-Dream/p/11267053.html