java-httpgetpost-picture byte stream upload

Source: Internet
Author: User

In Java program development often used in the interaction with the server, the main thing is to pass the corresponding parameter request to obtain the corresponding results to be processed

You can use GET requests with POST requests, note! The GET request here is not through the browser interface but is set in the program code, to achieve the purpose of the GET request, specifically please refer to the following description

The following get and post requests need to be introduced with the package:

Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.URLDecoder;ImportOrg.apache.commons.io.output.ByteArrayOutputStream;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.HttpStatus;Importorg.apache.http.client.ClientProtocolException;ImportOrg.apache.http.client.methods.CloseableHttpResponse;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;ImportOrg.apache.http.entity.ContentType;Importorg.apache.http.entity.StringEntity;ImportOrg.apache.http.entity.mime.MultipartEntityBuilder;ImportOrg.apache.http.entity.mime.content.StringBody;Importorg.apache.http.impl.client.DefaultHttpClient;Importorg.apache.http.impl.client.HttpClients;ImportOrg.apache.http.util.EntityUtils;

GET Request:

/*** Normal and easy to use HttpGet to send a GET request to the server to pass the parameters directly after the URL assembled on it OK *@paramHttpurl*/     Public Staticstring HttpGet (String httpurl) {Httpurl= "HTTP://192.168.199.138/WEIXIN/TEST.PHP?APPID=APPIDAAAA&SECRET=SECRETBBBB"; HttpGet HttpGet=NewHttpGet (Httpurl); Closeablehttpresponse Chresponse=NULL; String result=NULL; Try{chresponse=Httpclients.createdefault (). Execute (httpget); if(Chresponse.getstatusline (). Getstatuscode () ==200) {result=entityutils.tostring (Chresponse.getentity ()); }        } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally {            if(Chresponse! =NULL){                Try{chresponse.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        if(Result! =NULL) {System.out.println ("Results returned result==" +result); returnresult; }Else{System.out.println ("Request no results returned"); return""; }    }                /*** Shown to call HttpGet here the Send execution execut is different from the simple method above, * Pass parameters are directly assembled on the URL to pass on it *@paramHttpurl *@return     */@SuppressWarnings ("Deprecation")     Public Staticstring Httpgetshow (String httpurl) {//httpurl= ""; Defaulthttpclient Client=Newdefaulthttpclient (); HttpResponse Response=NULL; String result=NULL; Try {                        //send a GET requestHttpGet HttpGet =NewHttpGet (Httpurl);//the DifferenceResponse=Client.execute (HttpGet); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {Result=entityutils.tostring (Response.getentity ()); Httpurl= Urldecoder.decode (Httpurl, "UTF-8"); }        } Catch(IOException e) {e.printstacktrace (); }finally{client.close (); }        if(Result! =NULL){            returnresult; }Else{            return""; }    }

POST request:

/*** Do not show the use of HttpPost will default to submit the request by the way of post, * passed parameters to the form of Key:value to pass parameters *@paramHttpurl *@paramImagebyte can pass files such as pictures, which are passed in the form of byte arrays*/@SuppressWarnings ({"Deprecation" })     Public StaticString HttpPost (String Httpurl,byte[] imagebyte) {Httpurl= "http://192.168.199.138/weixin/test.php"; HttpPost HttpPost=NewHttpPost (Httpurl); bytearraybody image = new Bytearraybody (Imagebyte,contenttype.application_json, "image.jpg");// When you pass the picture, you can upload it here and image.jpg it by yourself.String AppID= "AppID"; String Secret= "Secret"; Stringbody Appidbody=Newstringbody (Appid,contenttype.application_json); Stringbody Secretbody=Newstringbody (Secret,contenttype.application_json); Multipartentitybuilder Me=multipartentitybuilder.create (); Me.addpart ("image", image)//image parameter for the server to obtain the key through the image of the parameter can be obtained to pass the stream of bytes, here is not necessarily the image, your server use what the corresponding parameters can be given . Addpart ("AppID", Appidbody). Addpart ("Secret", Secretbody); Defaulthttpclient Client=Newdefaulthttpclient (); Httpentity reqentity=Me.build ();        Httppost.setentity (reqentity); HttpResponse Responseres=NULL; Try{responseres=Client.execute (HttpPost); } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{client.close (); }                intStatus =responseres.getstatusline (). Getstatuscode (); String ResultStr=NULL; if(Status = = 200) {             byte[] content; Try{content=getcontent (responseres); ResultStr=NewString (Content, "Utf-8"); System.out.println ("HttpPost returns the result = =:" +resultstr); } Catch(IOException e) {e.printstacktrace (); }        }                    if(ResultStr! =NULL){            returnResultStr; }Else{            return""; }    }        /*** The call HttpPost is displayed to use post to submit the request, and the requested parameters are assembled into a JSON string, * Direct use of stringentity to send parameters is not necessary to use the form of Key:value to set the request parameters, * in the service The service side uses Request.getinputstream () to parse the JSON string sent from the request, * because the stringentity is used to wrap the passed parameters *@paramHttpurl *@paramJsonparam*/@SuppressWarnings ({"Resource", "deprecation" })     Public Staticstring Httppostshow (String httpurl,string jsonparam) {Httpurl= "http://192.168.199.138/weixin/test.php"; Jsonparam= "{\" appid\ ": \" appidbbbb33333\ ", \" secret\ ": \" secretaaaaa3333\ "}";//Assemble a JSON string defaulthttpclient httpClient=Newdefaulthttpclient (); //here is the display of the call post to set the use Post submission requestHttpPost method =NewHttpPost (Httpurl); String result=NULL; Try {            if(NULL!=Jsonparam) {                //solve Chinese garbled problemstringentity entity =NewStringentity (Jsonparam.tostring (), "Utf-8")///This stringentity can be received on the server without Key:value form, can Request.getinputstream () to obtain processing the entire request and then parse can Entity.setcontentenc Oding ("UTF-8"); Entity.setcontenttype ("Application/json");            Method.setentity (entity); } HttpResponse Response=Httpclient.execute (method); Httpurl= Urldecoder.decode (Httpurl, "UTF-8"); if(Response.getstatusline (). Getstatuscode () = = 200) {                Try{result=entityutils.tostring (Response.getentity ()); } Catch(Exception e) {e.printstacktrace (); }            }        } Catch(IOException e) {e.printstacktrace (); }        if(Result! =NULL){            returnresult; }Else{            return""; }    }        Private Static byte[] getcontent (httpresponse response)throwsIOException {inputstream result=NULL; Bytearrayoutputstream out=NewBytearrayoutputstream (); Try{httpentity resentity=response.getentity (); if(Resentity! =NULL) {result=resentity.getcontent (); intLen = 0;  while(len = Result.read ())! =-1) {out.write (len); }                returnOut.tobytearray (); }        } Catch(IOException e) {e.printstacktrace (); Throw NewIOException ("GetContent exception", E); } finally{out.close (); if(Result! =NULL) {result.close (); }        }        return NULL; }

The above is the GET and POST request mode for HTTP in Java, HttpPost (String httpurl,byte[] imagebyte) This method can pass unstructured data, such as pictures, in the form of streams.

java-httpgetpost-picture byte stream upload

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.