Practical Walkthrough Java Invoke HTTP interface Post example

Source: Internet
Author: User
Tags getmessage readline tojson
To initiate a request:

Import Java.io.bufferedinputstream;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.PrintWriter; Import Java.net.httpurlconnection;import Java.net.url;import Java.text.simpledateformat;import Org.apache.http.util.textutils;import Com.alibaba.fastjson.jsonobject;import Cn.com.doone.tx.cloud.tool.common.util.md5util;import Java.util.collection;import Java.util.Date;public Class          Intfmain {//post Request method public static string post (string strurl, string params) {System.out.println (strURL);         SYSTEM.OUT.PRINTLN (params);        String result = "";                BufferedReader reader = null;        StringBuilder sb = new StringBuilder ();        BufferedReader in = null; try {URL url = new URL (strurl);//Create connection HttpURLConnection connection = (httpurlconnection) URL.O              Penconnection ();              Connection.setdooutput (TRUE); ConNection.setdoinput (TRUE);              Connection.setusecaches (FALSE);              Connection.setinstancefollowredirects (TRUE); Connection.setrequestmethod ("POST"); Set Request Mode Connection.setrequestproperty ("Accept", "Application/json"); Set the format of the received data Connection.setrequestproperty ("Content-type", "Application/json");              Sets the format for sending data connection.connect (); if (params! = NULL &&!)                Textutils.isempty (params)) {byte[] writebytes = Params.getbytes ();                Set file length//Connection.setrequestproperty ("Content-length", String.valueof (Writebytes.length));                OutputStream Outwritestream = Connection.getoutputstream ();                Outwritestream.write (Params.getbytes ());                Outwritestream.flush ();            Outwritestream.close ();      } int responsecode = Connection.getresponsecode ();                  InputStream inputstream = null; if (resPonsecode = =) {InputStream = new Bufferedinputstream (Connection.getinputstream ());      } else {inputstream = new Bufferedinputstream (Connection.geterrorstream ()); } in = new BufferedReader (new InputStreamReader (InputStream, "UTF-8"));        String Line;while (line = In.readline ()) = null) {result+=line;}        } catch (Exception e) {e.printstacktrace ();                } finally {if (reader! = null) {try {reader.close ();                } catch (IOException e) {e.printstacktrace ();    }}} return result; } public static void Main (string[] args) {//string url = "Http://localhost:28001/intf/send"; String url = "Http://###:##/gdctsWeb/intf/send"; long createtime = new Date (). GetTime (); Long reqtime = new Date (). GetTime ( ); String bodystr= "{\" creator\ ": \" 4\ ", \" operator\ ": \" 4\ ", \" operatetype\ ": \" add\ ", \" channelcode\ ": \" v7\ ", \" SyniD\ ": \" 556445\ ", \" name\ ": \" computer group 345\ ", \" password\ ": \" 345123\ ", \" registertime\ ": \" 2018-07-0121:00:00\ ", \" account \ ": \" account041\ ", \" custtype\ ": \" 2\ ", \" Bindnumber\ ": \" 15055556666\ ", \" groupcontact\ ": [{\" contactname\ ": \" Group Contact \ ", \" Contactnumber\ ": \" 155555555\ ", \" email\ ": \" 2222@qq.com\ ", \" occupation\ ": \" Leader\ ", \" qq\ ": \" 313131\ ", \" Remark\ ": \" Contact notes \ "}],\" groupinfoevt\ ": [{\" address\ ": \" community address \ ", \" areacode\ ": \" 111\ ", \" busiarea\ ": \" 222\ ", \" Citycode\ ": \" 322\ ", \" custindustry\ ": \" industry \ ", \" groupnature\ ": \" nature \ ", \" groupsize\ ": \" big \ ", \" name\ ": \" a group client \ ", \" Provincecode\ ": \" 1111\ ", \" registeredcapital\ ": \" capital \ ", \" Remark\ ": \" remarks \ ", \" zipcode\ ": \" 350000\ "}],\" members\ ": [{ \ "name\": \ "name \", \ "Contactnumber\": \ "111444\", \ "certype\": \ "1\", \ "cerno\": \ "6874268552552\", \ "sex\": \ "1\", \ "age \ ": \" 10\ "}],\" resource\ ": \" Introduction \ "}"; Jsonobject Paramjson = new Jsonobject (true); Jsonobject BODY = new Jsonobject (true); Body=jsonobject.parseobject (BODYSTR); Jsonobject head = new Jsonobject (true); String Intfcode = "crm_custgroup004"; String SyssEcret= "GRD01"; String syscode= "V7"; String Signori=syscode+intfcode+syssecret+reqtime; collection<object> values = Body.values (); for (Object v:values) {signori=signori+v.tostring ();} System.out.println (Signori); String sign = MD5UTIL.MD5 (Signori); String headstr= "{\" syscode\ ": \" "+syscode+" \ ", \" intfcode\ ": \" "+intfcode+" \ ", \" reqtime\ ": \" "+reqtime+" \ "\" sign\ " : \ "" +sign+ "\"} "; Head=jsonobject.parseobject (HEADSTR);p aramjson.put (" Head ", head);p aramjson.put (" body ", body); try {String json = paramjson.tojsonstring (); String Postwithjson = post (URL, JSON); System.out.println (Postwithjson);} catch (Exception e) {e.printstacktrace ();}}}

Receiving party:

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.net.urldecoder;import Java.text.simpledateformat;import Java.util.date;import Java.util.Enumeration;import Java.util.hashmap;import Java.util.linkedhashmap;import Java.util.list;import Java.util.Map;import Javax.servlet.http.httpservletrequest;import Javax.servlet.jsp.tagext.trycatchfinally;import Org.apache.http.protocol.http;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.boot.autoconfigure.enableautoconfiguration;import Org.springframework.stereotype.Controller ; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.responsebody;import Com.alibaba.fastjson.jsonobject;import Cn.com.doone.tx.cloud.system.service.intfconfigservice;import cn.com.doone.tx.cloud.system.utils.JsonUtils; Import Cn.com.doone.tx.cloud.system.utils.serverheadersyn;import Cn.com.doone.tx.cloud.system.utils.ServerRespSyn; Import Cn.com.doone.tx.cloud.system.evt.requestjsonevt;import Cn.com.doone.tx.cloud.system.service.intfconfiglogservice;import Cn.com.doone.tx.cloud.tool.common.invoke.serverresp;import Cn.com.doone.tx.cloud.tool.common.util.Md5Util; Import cn.com.doone.tx.cloud.tool.web.base.basecontroller;// V7 System Sync Interface @controller@enableautoconfiguration@requestmapping ("/intf") public class Intfconfigcontroller extends Basecontroller {@AutowiredIntfConfigService intfconfigservice; @AutowiredIntfConfigLogService intfconfiglogservice ; @RequestMapping ("send") @ResponseBodypublic serverrespsyn<object> Send (HttpServletRequest request) throws IOException {serverrespsyn<object> respV7 = new serverrespsyn<> (); Serverheadersyn Respv7header = new Serverheadersyn (); serverresp<object> Resplogadd = new serverresp<> (); Serverresp<object> resp = new serverresp<> (); hashmap<string, object> pram = new hashmap<string, object> ();//Read request content BufferedReader br = new BufferedReader(New InputStreamReader (Request.getinputstream ())); String line = null; StringBuilder sb = new StringBuilder (line = Br.readline ())! = null) {sb.append (line);} Decodes the data string reqbody = Sb.tostring (); String str = Urldecoder.decode (Reqbody, HTTP. UTF_8); Requestjsonevt jsonevt = Jsonutils.fromjson (str, requestjsonevt.class); Map<string, object> head = Jsonevt.gethead (); map<string, object> BODY = Jsonevt.getbody (); String syssecret= "GRD01"; String signmy =head.get ("Syscode"). ToString () +head.get ("Intfcode"). ToString () + Syssecret +head.get ("Reqtime"). ToString (); String sign = head.get (' sign '). toString (); for (Object m:body.values ()) {signmy=signmy+ Jsonutils.tojson (m);} Try {serverresp<object> respconfiglist = intfconfigservice.getintfconfiglist (pram); list<linkedhashmap<string, object>> list = (list<linkedhashmap<string, Object>>) Respconfiglist.getbody (); if (Md5util.md5 (signmy). Equals (sign)) {for (linkedhashmap<string, object> Linkedhashmap:List) {if (Head.get ("Intfcode"). Equals (Linkedhashmap.get ("Intfcode"))) {hashmap<string, object> pramlog = new Hashmap<string, object> (); hashmap<string, object> pramLog1 = new hashmap<string, object> (); linkedhashmap<string, object> maplog = new linkedhashmap<> (); try {pramlog.put ("Callsystemcode", "V7"); Pramlog.put ("Intfsystemcode", "CRM");p ramlog.put ("Intfurl", Linkedhashmap.get ("Intfurl"));p ramlog.put ("IntfName") , Linkedhashmap.get ("Intfname"));p ramlog.put ("Intfcode", Linkedhashmap.get ("Intfcode"));p Ramlog.put (" Intfparamsin ", str);p ramlog.put (" creator ", 4);p ramlog.put (" operator ", 4); resplogadd = Intfconfiglogservice.addlog ( Pramlog); Maplog = (linkedhashmap<string, object>) resplogadd.getbody (); resp = Intfconfigservice.dosend (Body, Linkedhashmap.get ("Intfurl"). ToString ()), if (Resp.issuccess ()) {pramlog1.put ("id", Maplog.get ("id"));p Ramlog1.put ("Resdesc", "Call succeeded");p ramlog1.put ("status", Resp.gethead (). Getrespcode ());p ramlog1.put ("Intfparamsout", jsonutils. ToJson (RESP)); SimpleDateFormat formatter = new SimpleDateFormat ("Yyyymmddhhmmsssss"); String restime = Formatter.format (New Date ()), Respv7header.setrestime (Restime); Respv7header.setrespcode (0); Respv7header.setsign (sign); Respv7header.setrespmsg (Resp.gethead (). getrespmsg ()); Respv7.sethead (RespV7Header); Respv7.setbody (Resp.getbody ());} else {pramlog1.put ("id", Maplog.get ("id"));p ramlog1.put ("Resdesc", Resp.gethead (). Getrespmsg ());p ramlog1.put (" Status ", Resp.gethead (). Getrespcode ());p ramlog1.put (" Intfparamsout ", Jsonutils.tojson (resp)); SimpleDateFormat formatter = new SimpleDateFormat ("Yyyymmddhhmmsssss"); String restime = Formatter.format (New Date ()), Respv7header.setrestime (Restime); Respv7header.setrespcode (1); Respv7header.setsign (sign); Respv7header.setrespmsg (Resp.gethead (). getrespmsg ()); Respv7.sethead (RespV7Header); Respv7.setbody (Resp.getbody ());} } catch (Exception e) {pramlog1.put ("id", Maplog.get ("id"));p ramlog1.put ("Resdesc", "Call failed");p ramlog1.put ("status", "- 1 ");p ramlog1.put (" INTFPAramsout ", E.getmessage ()); SimpleDateFormat formatter = new SimpleDateFormat ("Yyyymmddhhmmsssss"); String restime = Formatter.format (New Date ()), Respv7header.setrestime (Restime); Respv7header.setrespcode (1); Respv7header.setsign (sign); Respv7header.setrespmsg (Resp.gethead (). getrespmsg ()); Respv7.sethead (RespV7Header); Respv7.setbody (E.getmessage ());} finally {Intfconfiglogservice.editlog (PRAMLOG1);}}} }else {SimpleDateFormat formatter = new SimpleDateFormat ("Yyyymmddhhmmsssss"); String restime = Formatter.format (New Date ()), Respv7header.setrestime (Restime); Respv7header.setrespcode (1); Respv7header.setsign (sign); Respv7header.setrespmsg ("Call failed"); Respv7.sethead (Respv7header); Respv7.setbody (" Security check Inconsistency ");}} catch (Exception e) {e.printstacktrace (); SimpleDateFormat formatter = new SimpleDateFormat ("Yyyymmddhhmmsssss"); String restime = Formatter.format (New Date ()), Respv7header.setrestime (Restime); Respv7header.setrespcode (1); Respv7header.setsign (sign); Respv7header.setrespmsg ("Call failed"); Respv7.sethead (reSpv7header); Respv7.setbody (E.getmessage ());} return respV7;}}
Related Article

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.