Java sends httpclient request and receives request result process

Source: Internet
Author: User

The following for myself in the work of writing business code, is not universal, only for their next use can have a search, and is in trouble with the programmer to learn from.

Recommend a better blog to everyone to see:

Http://blog.sina.com.cn/s/blog_75a8cfac01013aim.html

http://blog.csdn.net/fireelement/article/details/2497136

Http://www.2cto.com/kf/201206/136879.html

http://284772894.iteye.com/blog/1744114

1. Write a Httprequestutils tool class, including post requests and get requests

package com.brainlong.framework.util.httpclient;import net.sf.json.jsonobject;import  org.apache.commons.httpclient.httpstatus;import org.apache.http.httpresponse;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.defaulthttpclient;import  org.apache.http.util.entityutils;import org.slf4j.logger;import org.slf4j.loggerfactory;import  java.io.ioexception;import java.net.urldecoder;public class httprequestutils {     private static logger logger = loggerfactory.getlogger ( httprequestutils.class);     //Log Records     /**      * httpPost     *  @param  url   Paths       *  @param  jsonParam  parameter      *  @return      */    public static jsonobject  httppost (String url,jsonobject jsonparam) {         Return httppost (url, jsonparam, false);     }    /**      * post Request      *  @param  url          url address      *  @param  jsonparam       Parameters      *  @param  noNeedResponse      do not need to return results      *  @return      */     public static jsonobject httppost (string url,jsonobject jsonparam,  Boolean noneedresponse) {        //post request return results          defaulthtTpclient httpclient = new defaulthttpclient ();         jsonobject jsonresult = null;        httppost  method = new httppost (URL);         try {             if  (Null != jsonparam)  {                // Solve Chinese garbled problem                  Stringentity entity = new stringentity (jsonparam.tostring (),  "Utf-8");                 entity.setcontentencoding ( "UTF-8");                 Entity.setcontenttype ("Application/json");                 Method.setentity (Entity);            }             HttpResponse result =  Httpclient.execute (method);             url =  urldecoder.decode (url,  "UTF-8");             /** the request was sent successfully and received a response **/            if  ( Result.getstatusline (). Getstatuscode ()  == 200)  {                 String str =  "";                 try {                     /** read the JSON string data returned by the server **/                     str =  Entityutils.tostring (Result.getentity ());                     if  (Noneedresponse)  {                          return null;                     }                     /** converts a JSON string to a JSON object **/                     jsonresult =  jsonobject.fromobject (str);  &Nbsp;              } catch  ( Exception e)  {                     logger.error ("POST request submission failed:"  + url, e);                 }             }        } catch  ( Ioexception e)  {            logger.error ("POST request submission failed:"  + url, e);        }         return jsonresult;    }    /**      *  send get requests      *  @param  url      Path      *  @return      */    public static  Jsonobject httpget (string url) {        //get request return result          JSONObject jsonResult = null;         try {             Defaulthttpclient client = new defaulthttpclient ();             //Send GET Request              httpget request = new httpget (URL);             httpresponse response = client.execute (Request);             /** the request was sent successfully and received a response **/             if  (Response.getstatusline () Getstatuscode ()  == HTTPSTATUS.SC_OK)  {                 /** read the JSON string data returned by the server **/                 String  Strresult = entityutils.tostring (Response.getentity ());                 /** converts a JSON string to a JSON object **/                 jsonresult = jsonobject.fromobject (strresult);                 Url = urldecoder.decode (url,  "UTF-8");             } else {                 logger.Error ("Get request Submission failed:"  + url);             }         } catch  (ioexception e)  {             logger.error ("Get Request Submission failed:"  + url, e) ;        }        return  jsonresult;    }}

2. Write the business code to send the HTTP request

3. MVC configuration File Settings Controller Scan directory

<!--automatically scan and scan only @controller--><context:component-scan base-package= "Com.wiselong.multichannel" Use-default-filters= "false" ><context:include-filter type= "annotation" expression= " Org.springframework.stereotype.Controller "/></context:component-scan>

4. Receiving HTTP Requests

Receive a POST request

@Controller @requestmapping (value =  "/api/platform/exceptioncenter/exceptioninfo") public class  exceptioninfocontroller {    //Injection      @Autowired      private ExceptionInfoBiz exceptionInfoBiz;    /**      *  Create exception Information request      *  @param  requestBody  Request message content       *  @param  request  Request message Headers      *  @return  jsonObject     */     @RequestMapping (             value= "/create",             method = RequestMethod.POST    )      public modelandview createexceptioninfo (@RequestBody  String requestBody,  Httpservletrequest request)  {        JSONObject jsonObject =  Jsonobject.fromobject (requestbody);        comexceptioninfo  Comexceptioninfo = new comexceptioninfo ();         Comexceptioninfo.setprojectname (jsonobject.getstring ("ProjectName"));         comexceptioninfo.settagname (jsonobject.getstring ("TagName"));         exceptioninfobiz.insert (comexceptioninfo);         //return request result         jsonobject result= new jsonobject ();         result.put ("Success",  "true");         return new modelandview ("",  responseutilshelper.jsonsuccess (Result.toString () ));     }  }


Receiving a GET request

@Controller @requestmapping (value= "/api/platform/messagecenter/messages/sms") public class  smscontroller {     @Autowired     SmsSendBiz smsSendBiz;     /**     *  receive mobile phone number and content insert a record into the SMS Send table       *  @param  requestbody  Request message content      *  @param  request  Request message Headers      *  @return  jsonObject     */      @RequestMapping (            value= "/ Send ",             method= requestmethod.get     )     public modelandview sendsms (@RequestBody   String requestbody, httpservletrequest request)  {         //gets the request URL and the parameters that are transmitted after the URL  &nbsP;      string url = request.getrequesturl ()  +  "?"  + request.getquerystring ();        url =  Buildrequesturl.decodeurl (URL);         string telephone =  requestutils.getstringvalue (request,  "Telephone");         String content = requestutils.getstringvalue (request,  "content");         smssendbiz.insertttmsquequ (telephone,content);         return new modelandview ("",  responseutilshelper.jsonresult ("",  true));     }}


Java sends httpclient request and receives request result process

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.