HttpClient Post GET request call

Source: Internet
Author: User
Tags http post

Package Com.paic.nets.common.esg;import Com.alibaba.fastjson.json;import Com.alibaba.fastjson.jsonobject;import Com.paic.pafa.app.lwc.core.util.collectionutils;import Org.apache.commons.httpclient.httpclient;import Org.apache.commons.httpclient.httpstatus;import Org.apache.commons.httpclient.namevaluepair;import Org.apache.commons.httpclient.uriexception;import Org.apache.commons.httpclient.methods.getmethod;import Org.apache.commons.httpclient.methods.postmethod;import Org.apache.commons.httpclient.params.HttpMethodParams; Import Org.apache.commons.httpclient.util.uriutil;import Org.apache.commons.lang.stringutils;import Org.directwebremoting.util.logger;import Java.util.hashmap;import java.util.map;/** * ESG calls public class */public class    Esgaccesser {private static final Logger Logger = Logger.getlogger (Esgaccesser.class);    private static final String Http_post = "POST";    Private static final map<string, string> token_cache = new hashmap<string, string> (); public static Final String error_token = "13002";    public static final String Invalid_token = "13012";    public static final String ret_status = "RET" for ESG platform;    ESG Platform Returns a code that identifies success public static final String status_success = "0";    Private String Gettokenurl;    Private String Accessurl;    Private String Vuserid;    Private String Vuserpassword;     /** * Call the Extranet tool class * * @param esgurlcode ESG Platform Registered interface code * @param paramsmap Incoming parameter * @param the type of HttpMethod request * @return return JSON results * @throws Exception */public string Inaccessout (string esgurlcode, Map Paramsmap, Strin G HttpMethod) throws Exception {if (Stringutils.isblank (esgurlcode) | |        Stringutils.isblank (HttpMethod)) {return "";        } String resultstring = Invoke (Esgurlcode, Paramsmap, HttpMethod);        Jsonobject jsonobject = Json.parseobject (resultstring);        String retstatus = jsonobject.getstring (ret_status);       13002: Illegal access_token 13012: Defunct invalid Access_token if (error_token.equals (retstatus) | |            Invalid_token.equals (Retstatus)) {Getaccesstoken ();            Resultstring = Invoke (Esgurlcode, Paramsmap, HttpMethod);            Jsonobject = Json.parseobject (resultstring);        Retstatus = jsonobject.getstring (ret_status); } if (!        Status_success.equals (Retstatus)) {return "";    } return jsonobject.getstring ("data");        }/** * received token of recognition (valid for 1 hours) */private void Getaccesstoken () {stringbuffer url = new StringBuffer (); Url.append (Gettokenurl). Append ("? client_id=" + Vuserid). Append ("&grant_type=out_agent"). Append (        "&client_secret="). Append (Vuserpassword);        Logger.info ("Start getting token:url:[[" + URL);        String Tokenresult = doget (url.tostring (), NULL);        Logger.info ("End Get token:tokenresult:[[" + tokenresult);        Jsonobject jsonobject = Json.parseobject (Tokenresult);     String retstatus = jsonobject.getstring (ret_status);   if (!        Status_success.equals (Retstatus)) {return;    } token_cache.put ("TOKEN", Jsonobject.getjsonobject ("Data"). GetString ("Access_token")); }/** * Execute HTTP request * @param esgurlcode ESG Platform Interface encoding * @param paramsmap parameter * @param httpmethod call mode p OST Get * @return */private string Invoke (String Esgurlcode, Map paramsmap, String httpmethod) {LOGGER . info ("Start call: esgurlcode:[[" + Esgurlcode + "]],paramsmap:[[" + json.tojsonstring (paramsmap) + "]],httpmethod        : [["+ HttpMethod);        StringBuffer url = new StringBuffer ();                Url.append (Accessurl). Append (Esgurlcode). Append ("? esg_outer_access_token="). Append (Token_cache.get ("token"))        . Append ("&esg_outer_request_id="). Append (System.currenttimemillis ());        String resultstring;        if (Http_post.equalsignorecase (HttpMethod)) {resultstring = DoPost (url.tostring (), paramsmap); } else {resultstring = Doget (url.tOstring (), paramsmap);        } logger.info ("Result call: resultstring:[[" + resultstring);    return resultstring; /** * Executes an HTTP GET request that returns the HTML * * @param URL request of the request URL * @param the params request query parameter, can be null * @re Turn return Request Response HTML */Private String doget (string url, map<string, string> params) {string queryString        = Geturlfromparamap (params);        GetMethod method = new GetMethod (URL);        String response = ""; try {if (Stringutils.isnotblank (queryString)) {method.setquerystring (uriutil.encodequery (query            String));            } method.addrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");            Method.addrequestheader ("Accept", "application/json;charset=utf-8");            HttpClient client = new HttpClient ();            Client.getparams (). Setparameter (Httpmethodparams.http_content_charset, "utf-8");            Client.executemethod (method); If (Method.getstatuscode () = = HTTPSTATUS.SC_OK)            {response = method.getresponsebodyasstring (); }} catch (Uriexception e) {logger.error ("when executing an HTTP GET request, the encoded query string [[" + QueryString + "]] has an exception!        ", e); } catch (Exception e) {logger.error ("Execute HTTP GET request [[" + URL +]], an exception occurred!        ", e);        } finally {method.releaseconnection ();    } return response; The/** * GET request resolves the Map parameter * @param params * @return */private String Geturlfromparamap (map<string, St        Ring> params) {if (Collectionutils.isempty (params)) {return "";        } stringbuffer queryString = new StringBuffer ();        Querystring.append ("?"); For (map.entry<string, string> entry:params.entrySet ()) {Querystring.append ("&"). Append (entry.getk        EY ()). Append ("="). Append (Entry.getvalue ());    } return querystring.tostring ();    /** * Executes an HTTP POST request that returns the HTML of the request response * * @param URL requested URL address * @param params request query parameter, can be NULL * @return return Request Response HTML */private String DoP        OST (String URL, map<string, string> params) {namevaluepair[] valuepairs = Getpostpair (params);        Postmethod method = new Postmethod (URL);        if (valuepairs! = null) {method.setrequestbody (valuepairs); } method.addrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");//Key Code METHOD.A        Ddrequestheader ("Accept", "application/json;charset=utf-8");//Key code String response = "";            try {HttpClient client = new HttpClient ();            Client.getparams (). Setparameter (Httpmethodparams.http_content_charset, "utf-8");            Client.executemethod (method);            if (method.getstatuscode () = = HTTPSTATUS.SC_OK) {response = method.getresponsebodyasstring (); }} catch (Exception e) {logger.error ("executes HTTP POST request [[" + URL +]], occursAbnormal!        ", e);        } finally {method.releaseconnection ();    } return response; }/** * POST request Resolution MAP parameter * @param params * @return */private namevaluepair[] Getpostpair (map<string        , string> params) {if (Collectionutils.isempty (params)) {return new namevaluepair[0];        } namevaluepair[] Pairs = new namevaluepair[params.size ()];        Namevaluepair Temppair;        int size = 0; For (map.entry<string, string> entry:params.entrySet ()) {Temppair = new Namevaluepair (Entry.getkey (),            Entry.getvalue ());            Pairs[size] = Temppair;        size++;    } return pairs;    } public String Getgettokenurl () {return gettokenurl;    } public void Setgettokenurl (String gettokenurl) {this.gettokenurl = Gettokenurl;    } public String Getaccessurl () {return accessurl; } public void Setaccessurl (String accessurl) {This.accessurl = ACCessurl;    } public String Getvuserid () {return vuserid;    } public void Setvuserid (String vuserid) {this.vuserid = Vuserid;    } public String Getvuserpassword () {return vuserpassword;    } public void Setvuserpassword (String vuserpassword) {This.vuserpassword = Vuserpassword; }}

  

HttpClient Post GET request call

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.