Java Http GET Post send request

Source: Internet
Author: User

Java Http GET Post send request

This article wrote 1 Java send GET request and 2 Java send POST request, novice, do not like to spray!

Background:

This is a use of the magic Treasure to pay the demo, the first need to mobile to submit the marketplace orders, request the platform signature interface to sign and get the necessary elements of payment, the payment company returns the information to return to the mobile side of these elements, the mobile start Payment company SDK for payment transactions, followed by the receipt of transaction results notification message.

Description
  • Get core: Closeablehttpclient and Closeablehttpresponse,httpget
  • Post core: HttpURLConnection and HttpPost
Function Step Description
  1. The first step: Get request signature operation from the server signature interface;
  2. The second step: Get request to the magic treasure to pay the necessary elements to obtain payment;
  3. Step three: Post Verification Magic return signature information, tamper-proof
static variables
  • Order information: private static String Trandata = "XML order Information";
  • Signature interface: private static String Signurl = "Http://10.3.30.17:8099/chpay/v1/pay/mobao/sign";
  • Verification interface private static String Verifyurl = "Http://10.3.30.17:8099/chpay/v1/pay/mobao/signature/verify";
  • Magic Treasure Interface: private static String Mobaourl = "Http://182.148.123.7:8132/service";
First step: Signature
    • Sign a trade order with a certificate from the payer prior to trading
/*** Sign Order information * / Public StaticJsonobjectTesthttpget(String data)throwsunsupportedencodingexception {closeablehttpclient httpClient = Httpclients.custom (). Disablecontentcompression (). Bu        ILD (); StringBuffer Qurl =NewStringBuffer (Signurl); Qurl.append ("? Trandata="+ Urlencoder.encode (data,"UTF-8")); HttpGet HttpGet =NewHttpGet (NewString (Qurl));Try{Closeablehttpresponse HttpResponse = Httpclient.execute (HttpGet); httpentity entity = httpresponse.getentity ();//return contentString res = entityutils.tostring (Entity,"UTF-8");returnJsonobject.parseobject (RES); }Catch(IOException e)        {E.printstacktrace (); }return NULL; }
Step two: Get Payment essentials
    • Use the format specified by the payer, request payment of the company interface after signing, pay the necessary elements of payment, payment of company return elements and signature information
 Public StaticStringgetpayelements(Jsonobject JSON)throwsunsupportedencodingexception {if(Json.containskey ("Message") && Json.containskey ("Signature") {String message = json.getstring ("Message"); String signature = json.getstring ("Signature"); String param ="Message="+ Message +"&signature="+ signature; String paramencode = Urlencoder.encode (param,"UTF-8");            Closeablehttpclient httpClient = Httpclients.custom (). Disablecontentcompression (). build (); StringBuffer Qurl =NewStringBuffer (Mobaourl); Qurl.append ("? message="+ urlencoder.encode (Message,"UTF-8")); Qurl.append ("&signature="+ Urlencoder.encode (signature,"UTF-8")); HttpGet HttpGet =NewHttpGet (NewString (Qurl));Try{Closeablehttpresponse HttpResponse = Httpclient.execute (HttpGet); httpentity entity = httpresponse.getentity ();//return contentString res = entityutils.tostring (Entity,"UTF-8");returnRes }Catch(IOException e)            {E.printstacktrace (); }        }return NULL; }
Step Three: Verification
    • When the payment element is acquired, the company returns the signature information and needs to be checked to prevent the information from being tampered with.
 Public StaticJsonobjectverifysign(Jsonobject Jsonobject) {if(Jsonobject.containskey ("Message") && Jsonobject.containskey ("Signature") {String message = jsonobject.getstring ("Message"); String signature = jsonobject.getstring ("Signature");Try{//Create connectionURL url =NewURL (Verifyurl);                HttpURLConnection connection = (httpurlconnection) URL. OpenConnection (); Connection.setdooutput (true); Connection.setdoinput (true); Connection.setrequestmethod ("POST"); Connection.setusecaches (false); Connection.setinstancefollowredirects (true);/ /Connection.setrequestproperty ("Accept", "Application/json");//Set the format of the received dataConnection.setrequestproperty ("Content-type","Application/json"); Connection.connect ();//post RequestDataOutputStream out =NewDataOutputStream (Connection.getoutputstream ()); Jsonobject obj =NewJsonobject (); Obj.put ("Message", message); Obj.put ("Signature", signature);                Out.writebytes (Obj.tostring ());                Out.flush (); Out.close ();//Read responseBufferedReader reader =NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));                String lines; StringBuffer SB =NewStringBuffer (""); while((lines = Reader.readline ())! =NULL) {lines =NewString (Lines.getbytes (),"Utf-8");                Sb.append (lines); } reader.close ();//DisconnectConnection.disconnect ();returnJsonobject.parseobject (Sb.tostring ()); }Catch(Malformedurlexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Unsupportedencodingexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }return NULL; }
Attached: Another POST request method
 Public StaticStringPost(string json, string URL)throwsexception{stringentity entity =NewStringentity (JSON,"Utf-8"); Entity.setcontenttype ("Application/json"); Defaulthttpclient client =NewDefaulthttpclient (); HttpPost HttpPost =NewHttpPost (URL);        Httppost.setentity (entity);        HttpResponse response = Client.execute (HttpPost);        InputStream InputStream = response.getentity (). getcontent (); StringBuffer buffer =NewStringBuffer (); InputStreamReader Inputreader =NewInputStreamReader (InputStream); BufferedReader Bufferreader =NewBufferedReader (Inputreader); String str; while(str = bufferreader.readline ())! =NULL) {buffer.append (str);        } bufferreader.close (); String jsonout = buffer.tostring ();returnJsonout; }

My Contact information:
-Q q:1250052380
-Email: [Email protected]

Java Http GET Post send request

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.