When an HTTP request is requested, the object parameter by reflection stitching tool

Source: Internet
Author: User
Tags dateformat finally block


Package Org.te;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.text.simpledateformat;import Java.util.date;public class GetParamter {public static void Main (string[] args) throws Exception {User user = new User (); User.setid (1); User.setname ("name"); String param = Getparamter.getpara (user); System.out.println (param);} public static String Getpara (gen<?> Gen) throws Exception {class<?> Clz = Gen.getgentype (). GetClass (); StringBuffer result = new StringBuffer (512); field[] field = Clz.getdeclaredfields (); Result.append ("? ="); for (field F:field) {Object o = Getmethodvalue (CLZ, GEN.GETG Entype (), F.getname ()); if (o! = null &&! "). Equals (O.tostring ())) {result.append (O + "&");}} Result.delete (Result.length ()-1, Result.length ()); return result.tostring (); /** * Get values based on fields * * @param CLZ * @param o * @param field * @return */@SuppressWarnings ("Rawtypes") public static Object Getm Ethodvalue (Class Clz,Object o, String field) throws Nosuchmethodexception, Securityexception,illegalaccessexception, illegalargumentexception,invocationtargetexception {Character Charss = Field.charat (0); field = Field.replacefirst ( Charss.tostring (), Character.touppercase (CHARSS) + "");//Get Value @suppresswarnings ("unchecked") Method GetMethod = Clz.getdeclaredmethod ("Get" + field, new class[] {}); Object value = Getmethod.invoke (o, new object[] {}); return value;} public static string Convertype (Object value, String dateformat) {string rresult = "";//if (value instanceof Integer)//{ int result = (Integer) value;//return result;////} else if (value instanceof Float)//{//float result = (float) valu e;//return result;////} else if (value instanceof Double)//{//double result = (double) value;//return result;////} E LSE if (value instanceof long)//{//Long result = (long) value;//return result;//}//if (value instanceof Boolean)//{/ /Boolean result = (Boolean) value;//return result;////} elseif (value inStanceof date) {Date date = (date) value;if ("". Equals (DateFormat) | | NULL = = DateFormat) {DateFormat = "yyyy-mm-dd";} Illegalargumentexceptionsimpledateformat SDF = new SimpleDateFormat (dateformat); rresult = Sdf.format (date);} else if (value instanceof byte[]) {//} else {return value + "";} return rresult;}}

Package Org.te;public interface Gen<t> {T getgentype ();}

Package Org.te;public class User implements gen<user> {private integer id;private String name;public integer getId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic User Getgentype () {return this;} @Overridepublic String toString () {return "User [id=" + ID + ", name=" + name + "]";}}

HTTP-----------------------

Package Org.te;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstreamreader;import Java.io.printwriter;import java.net.url;import java.net.urlconnection;import Java.util.list;import java.util.Map; public class HttpRequest {/** * a request to send a GET method to a specified URL * * @param URL * Send the requested URL * @param pa     RAM * Request parameters, request parameters should be in the form of name1=value1&name2=value2.        * The response result of the remote resource represented by the @return URL */public static string Sendget (string URL, string param) {string result = "";        BufferedReader in = null;            try {String urlnamestring = URL + "?" + param;            URL realurl = new URL (urlnamestring);            The connection between open and URL urlconnection connection = Realurl.openconnection ();            Set the generic request attribute Connection.setrequestproperty ("accept", "*/*");            Connection.setrequestproperty ("Connection", "keep-alive");              Connection.setrequestproperty ("User-agent",      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;            SV1) ");            Establish the actual connection connection.connect ();            Get all response header fields Map<string, list<string>> Map = Connection.getheaderfields (); Traverse all response header fields for (String Key:map.keySet ()) {System.out.println (key + "--->" + map.get (key            ));                    }//define BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (            Connection.getinputstream ()));            String Line;            while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {System.out.println ("Send GET request exception!)            "+ e);        E.printstacktrace (); }//Use finally block to close the input stream finally {try {if (in! = null) {In.clos                E ();            }} catch (Exception E2) {e2.printstacktrace ();}} return result;            /** * Request to send a POST method to the specified URL * * @param URL * Send the requested URL * @param param *     Request parameters, request parameters should be in the form of name1=value1&name2=value2.        * The response result of the remote resource represented by the @return */public static string Sendpost (string url, string param) {printwriter out = null;        BufferedReader in = null;        String result = "";            try {URL realurl = new URL (URL);            The connection between open and URL URLConnection conn = realurl.openconnection ();            Set the generic request attribute Conn.setrequestproperty ("Referer", "http://www.baidu.com");            Conn.setrequestproperty ("Accept", "*/*");            Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;            SV1) ");            The Send POST request must be set to the following two lines conn.setdooutput (true);            Conn.setdoinput (TRUE); Get URLConnection object correspondingThe output stream out = new PrintWriter (Conn.getoutputstream ());            Send request parameter out.print (param);            Flush output Stream Buffer Out.flush (); Defines the BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (conn.getinput            Stream ()));            String Line;            while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {System.out.println ("send POST request exception!            "+e);        E.printstacktrace (); }//Use finally block to close the output stream, input stream finally{try{if (out!=null) {Out.close                ();                } if (In!=null) {in.close ();            }} catch (IOException ex) {ex.printstacktrace ();    }} return result; } public static void Main (string[] args) {//Send GET request//String s=httprequEst.sendget ("Http://192.168.20.249:8888/api/User/Login", "loginname=en&loginpwd=en");//                System.out.println (s); Send POST request String sr=httprequest.sendpost ("Http://192.168.20.249:8888/api/User/Login", "loginname=en&loginpwd        =en ");    System.out.println (SR); }}


When an HTTP request is requested, the object parameter by reflection stitching tool

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.