JAVA sends HTTP GET/POST requests, invokes HTTP interfaces, methods __java

Source: Internet
Author: User
three examples-java send HTTP get/post request, call HTTP interface, method

Example 1: Using HttpClient (Commons-httpclient-3.0.jar
Jar Download Address: http://download.csdn.net/download/capmiachael/9760550)

Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;

Import Java.io.InputStream;
Import org.apache.commons.httpclient.HttpClient;
Import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
Import Org.apache.commons.httpclient.methods.PostMethod;

Import org.apache.commons.httpclient.methods.RequestEntity; public class Httptool {/** * send POST request * * @author Michael-----Csdn:http://blog.csdn.net/capmiachae
     L * @param params * parameter * @param requesturl * Request Address * @param authorization * Power of Attorney * @return return result * @throws IOException/public static string Sendpost (String params , string Requesturl, String authorization) throws IOException {byte[] requestbytes = params.getbytes ("Utf-8"); Converts the parameter to binary stream httpclient httpclient = new HttpClient ();//client instantiation Postmethod Postmethod = new Postmethod (req Uesturl);
        Set Request Header Authorization Postmethod.setrequestheader ("Authorization", "Basic" + Authorization);
        Set Request Header Content-type Postmethod.setrequestheader ("Content-type", "Application/json");
        InputStream InputStream = new Bytearrayinputstream (requestbytes, 0, requestbytes.length); Requestentity requestentity = new Inputstreamrequestentity (InputStream, Requestbytes.length, "application/ Json Charset=utf-8 ");
        The request body postmethod.setrequestentity (requestentity); Httpclient.executemethod (Postmethod)//execute request InputStream Soapresponsestream = Postmethod.getresponsebodyasstream ()
        ;//Get the returned stream byte[] datas = null; try {datas = Readinputstream (Soapresponsestream);//read data from input stream} catch (Exception e) {E.P
        Rintstacktrace (); string result = new String (datas, "UTF-8");//returns the binary to string//print results//SYSTEM.OUT.PRINTLN (ResU

      LT);  return result; /** * Read data from input stream * * @param instream * @return * @throws Exception * * Public stat IC byte[] Readinputstream (InputStream instream) throws Exception {Bytearrayoutputstream OutStream = new ByteArray
        OutputStream ();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (len = instream.read (buffer))!=-1) {outstream.write (buffer, 0, Len);
        } byte[] data = Outstream.tobytearray ();
        Outstream.close ();
        Instream.close ();
    return data; }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70-71--72 73---74 75--76 1 2 3 4 5 6-7 8 9 10 2 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75-76

Example 2: Source: Open source China Teardream http://www.oschina.net/code/snippet_2266157_45252

Import Java.io.BufferedReader;
Import java.io.IOException;  
Import Java.io.InputStream;  
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;  
Import java.io.UnsupportedEncodingException;  
Import java.net.HttpURLConnection;
Import java.net.InetSocketAddress;
Import Java.net.Proxy; 
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.List;

Import Java.util.Map; /** * HTTP Request Tool class * @author snowfigure * @since 2014-8-24 13:30:56 * @version v1.0.1/public class Httprequestut
    Il {static Boolean proxyset = false;
    static String ProxyHost = "127.0.0.1";
    static int proxyport = 8087; /** * Code * @param source * @return/public static string UrlEncode (String source,string Enc  
        ODE) {String result = source;  
        try {result = Java.net.URLEncoder.encode (Source,encode);  
            catch (Unsupportedencodingexception e) {e.printstacktrace (); Return "0";  
    return result;  
        public static string URLENCODEGBK (string source) {string result = Source;  
        try {result = Java.net.URLEncoder.encode (source, "GBK");  
            catch (Unsupportedencodingexception e) {e.printstacktrace ();  
        return "0";  
    return result; /** * Initiates HTTP request fetch return result * @param req_url request Address * @return/public static String Httpreques  
        T (String req_url) {StringBuffer buffer = new StringBuffer ();  
            try {URL url = new URL (req_url);  

            HttpURLConnection httpurlconn = (httpurlconnection) url.openconnection ();  
            Httpurlconn.setdooutput (FALSE);  
            Httpurlconn.setdoinput (TRUE);  

            Httpurlconn.setusecaches (FALSE);  
            Httpurlconn.setrequestmethod ("get");  

            Httpurlconn.connect (); Converts the returned input flow to a string InputStream InputStream = Httpurlconn.getinputstream ();  
            InputStreamReader InputStreamReader = new InputStreamReader (InputStream, "utf-8");  

            BufferedReader BufferedReader = new BufferedReader (InputStreamReader);  
            String str = NULL;  
            while (str = Bufferedreader.readline ())!= null) {buffer.append (str);  
            } bufferedreader.close ();  
            Inputstreamreader.close ();  
            Releasing resources inputstream.close ();  
            InputStream = null;  

        Httpurlconn.disconnect ();  
        catch (Exception e) {System.out.println (E.getstacktrace ());  
    return buffer.tostring (); /** * Send HTTP request to get return input stream * @param requesturl request Address * @return InputStream * * Public stat  
        IC InputStream httprequestio (String requesturl) {InputStream inputstream = null; try {URL url = new URL (requeSturl);  
            HttpURLConnection httpurlconn = (httpurlconnection) url.openconnection ();  
            Httpurlconn.setdoinput (TRUE);  
            Httpurlconn.setrequestmethod ("get");  
            Httpurlconn.connect ();  
        Gets the returned input stream inputstream = Httpurlconn.getinputstream ();  
        catch (Exception e) {e.printstacktrace ();  
    return inputstream;            /** * Request to send a GET method to the specified URL * * @param URL * Send the requested URL * @param param *
     Request parameter, the request parameter should be the form of name1=value1&name2=value2. * @return The response result of the remote resource represented by the URL/public static string Sendget (string URL, string param) {String results = ""
        ;
        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 genusSexual 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 ();
            Gets all response header fields Map<string, list<string>> Map = Connection.getheaderfields (); Iterate through all the response header fields for (String Key:map.keySet ()) {System.out.println (key +--->) + map.get (k
            EY));
                    }//define BufferedReader input stream to read URL response in = new BufferedReader (New InputStreamReader (
            Connection.getinputstream ()));
            String Line;
            while (line = In.readline ())!= null) {result + = line; Exception e {System.out.println ("Send Get request exception.
            "+ e);
        E.printstacktrace ();
    }    Use the finally block to close the input stream finally {try {if (in!= null) {In.close
                ();
            } catch (Exception E2) {e2.printstacktrace ();
    } return result;            /** * Request * Send the Post method to the specified URL * * @param URL * Send the requested URL * @param param *
     Request parameter, the request parameter should be the form of name1=value1&name2=value2. * @param isproxy * Use proxy mode * @return The response result of a remote resource on behalf of/public static String Sendpost (Strin
        G URL, String param,boolean isproxy) {outputstreamwriter out = null;
        BufferedReader in = null;
        String result = "";
            try {URL realurl = new URL (URL);
            HttpURLConnection conn = null; if (IsProxy) {//using proxy mode @SuppressWarnings ("static-access") Proxy proxy = new Proxy (proxy.type . DIRECT. HTTP, New Inetsocketaddress (ProxyHost, ProxypoRT));
            conn = (httpurlconnection) realurl.openconnection (proxy);
            }else{conn = (httpurlconnection) realurl.openconnection ();
            //Open and URL connection//Send POST request must be set as follows two lines conn.setdooutput (true);
            Conn.setdoinput (TRUE);    Conn.setrequestmethod ("POST");
            Post method/Set Common request attribute Conn.setrequestproperty ("accept", "*/*");
            Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;
            SV1) "); Conn.setrequestp

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.