Android sends HTTP GET POST requests and uploads files via Multipartentitybuilder

Source: Internet
Author: User
Tags getmessage

After several days of the HTTP finally finished, the test is normal, but the preliminary use case test, because the following will be modified to first save the current version of the blog.

Post because of the need to import more than two package files, I used the latest httpmine4.3 found that many multipartentity related articles are early versions, some of the previous methods, although still available, but the new version has not been recommended to use, So all the new ways are multipartentitybuilder to deal with.

Httpmime-4.3.2.jar  


Download Address: http://hc.apache.org/downloads.cgi

Some mirrors may not open, the page can select the domestic. cn suffix of the domain name mirror server to download


If it's Android studio, here's a problem: Android Duplicate files copied in APK


After the test POST on the Chinese processing is also normal, no garbled found

Here's the complete code:

Zhttprequest.java

Package com.ai9475.util;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.HttpStatus;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.client.methods.HttpRequestBase;
Import Org.apache.http.entity.ContentType;
Import Org.apache.http.entity.mime.HttpMultipartMode;
Import Org.apache.http.entity.mime.MultipartEntityBuilder;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.params.BasicHttpParams;
Import Org.apache.http.params.HttpConnectionParams;
Import Org.apache.http.params.HttpParams;

Import Org.apache.http.protocol.HTTP;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.io.UnsupportedEncodingException;
Import Java.nio.charset.Charset;
Import Java.util.Iterator;
Import Java.util.Map;

Import Java.util.Set; /** * Created by ENOuz on 14-2-3.

    * * public class Zhttprequest {protected String URL = "";

    Protected Map<string, string> headers = null;

    protected int connectiontimeout = 5000;

    protected int sotimeout = 10000;

    protected int statusCode = 200; Protected String charset = HTTP.

    Utf_8;

    protected HttpGet HttpGet;

    protected HttpPost HttpPost;

    protected Httpparams httpparameters;

    protected HttpResponse HttpResponse;

    protected HttpClient httpclient;

    protected String inputcontent;
        /** * Set the current request link * * @param URL * @return/public zhttprequest seturl (String URL) {
        This.url = URL;
    return this; /** * Set HEADER information for request * * @param headers * @return/Public zhttprequest setheaders (M
        AP Headers) {this.headers = headers;
    return this; /** * Set the connection timeout * * @param timeout Unit (milliseconds), default 5000 * * @return/public ZHtTprequest setconnectiontimeout (int timeout) {this.connectiontimeout = timeout;
    return this; /** * Set the socket read Timeout * * @param timeout Unit (milliseconds), default 10000 * * @return/public Zhttpreq
        uest setsotimeout (int timeout) {this.sotimeout = timeout;
    return this; /** * Set the encoding format for the content * * @param charset default is UTF-8 * @return * * Public zhttprequest Setcha
        RSet (String charset) {this.charset = charset;
    return this; /** * Obtain HTTP Request response Information * * @return/public HttpResponse Gethttpresponse () {RET
    Urn This.httpresponse; /** * Get HTTP Client Connection Manager * * @return/public httpclient gethttpclient () {retur
    n This.httpclient; /** * Get the requested status code * * @return * * public int Getstatuscode () {return This.statusco
    De
   /** * Request data by Get method  * * @param URL * @return * @throws IOException */public string get (String URL) throws Ioexcepti
        On {//Set the link this.seturl (URL) of the current request;
        Instantiate get connection This.httpget = new HttpGet (This.url);
        Custom Configuration header information This.addheaders (this.httpget);
        Initialize client request this.inithttpclient ();
        Send HTTP Request This.httpresponse = This.httpClient.execute (this.httpget);
        Read Remote Data this.getinputstream ();
        Whether the remote request status code is normal if (This.statuscode!= httpstatus.sc_ok) {return null;
    //Returns all read to the string return this.inputcontent; 
    public string post (string URL, map<string, string> datas, map<string, string> files) throws IOException
        {this.seturl (URL);
        Instantiate get connection This.httppost = new HttpPost (This.url);
        Custom Configuration header information This.addheaders (this.httppost); Initialize client request This.initHttpClient ();
        Iterator iterator = Datas.entryset (). iterator ();
        Multipartentitybuilder Multipartentitybuilder = Multipartentitybuilder.create ();
        Multipartentitybuilder.setmode (httpmultipartmode.browser_compatible);
        Multipartentitybuilder.setcharset (Charset.forname (This.charset)); The Sent data while (Iterator.hasnext ()) {map.entry<string, string> Entry = (map.entry<string, St
            ring>) Iterator.next (); Multipartentitybuilder.addtextbody (Entry.getkey (), Entry.getvalue (), Contenttype.create ("Text/plain",
        Charset.forname (This.charset)));
            The//Sent file if (Files!= null) {iterator = Files.entryset (). iterator (); while (Iterator.hasnext ()) {map.entry<string, string> Entry = (map.entry<string, string>) ite
                Rator.next ();
                String path = Entry.getvalue (); if ("". Equals (path) | |
                Path = = null) continue; File file = new file (Entry.getvalue ());
            Multipartentitybuilder.addbinarybody (Entry.getkey (), file);
        }//Generate HTTP entity httpentity httpentity = Multipartentitybuilder.build ();
        Set the entity portion of the POST request this.httpPost.setEntity (httpentity);
        Send HTTP Request This.httpresponse = This.httpClient.execute (this.httppost);
        Read Remote Data this.getinputstream ();
        Whether the remote request status code is normal if (This.statuscode!= httpstatus.sc_ok) {return null;
    //Returns all read to the string return this.inputContent.toString ();  /** * Add header information for HTTP requests * * @param request */protected void Addheaders (httprequestbase
            Request) {if (this.headers!= null) {Set keys = This.headers.entrySet ();
            Iterator iterator = Keys.iterator ();
            Map.entry<string, string> Entry; while (Iterator.hasnext ()) {Entry = (map.entry<string, string>) Iterator.next ();
            Request.addheader (Entry.getkey (). ToString (), Entry.getvalue (). ToString ()); }}/** * Configuration request parameter/protected void SetParams () {this.httpparameters = new Ba
        Sichttpparams ();
        This.httpParameters.setParameter ("CharSet", This.charset);
        Set the connection request Timeout Httpconnectionparams.setconnectiontimeout (this.httpparameters, this.connectiontimeout);
    Sets the socket read Timeout httpconnectionparams.setsotimeout (this.httpparameters, this.sotimeout); /** * Initialize config client request/protected void Inithttpclient () {//configure HTTP Request Parameters This.setpar
        AMS ();
    Open a client HTTP request This.httpclient = new Defaulthttpclient (this.httpparameters);
    /** * Read Remote Data * * @throws IOException/protected void getInputStream () throws IOException {///receive remote input stream InputStream instream = This.httpResponse.getEntity (). getcontent ();
        Segmented read input stream data bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
        byte[] buf = new byte[1024];
        int len =-1;
        while (len = Instream.read (buf))!=-1) {baos.write (buf, 0, Len);
        ///Convert data to string save This.inputcontent = new String (Baos.tobytearray ());
        The data receives completes exits Instream.close ();
    Gets the status code returned by the request This.statuscode = This.httpResponse.getStatusLine (). Getstatuscode (); /** * Close Connection Manager release resource/protected void Shutdownhttpclient () {if (this.httpclient!= null &A
        mp;& This.httpClient.getConnectionManager ()!= null) {This.httpClient.getConnectionManager (). Shutdown ();
 }
    }
}

Mainactivity.java

I'll just write the incident section.

    public void DoClick (view view) {Zhttprequest request = new Zhttprequest ();
        String url = "";
        TextView TextView = (TextView) Findviewbyid (r.id.showcontent);
        String content = "Empty content";
                try {if (view.getid () = = r.id.doget) {url = "http://www.baidu.com";
            Content = "Get data:" + request.get (URL);
                else {url = "http://192.168.1.6/test.php";
                hashmap<string, string> datas = new hashmap<string, string> ();
                Datas.put ("P1", "abc");
                Datas.put ("P2", "Chinese");
                Datas.put ("P3", "ABC Chinese CBA");
                Datas.put ("Pic", This.picpath);
                Hashmap<string, string> files = new hashmap<string, string> ();
                Files.put ("file", This.picpath);
            Content = "Post data:" + request.post (URL, datas, files); The catch (IOException e) {content ="IO exception:" + E.getmessage ();
        catch (Exception e) {content = "Exception:" + E.getmessage ();
    } textview.settext (content); }

The This.picpath is the photo path String type in the specified SD card


Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Fill_parent" an droid:layout_height= "fill_parent" android:orientation= "vertical" > <scrollview android:layout_wi Dth= "Fill_parent" android:layout_height= "fill_parent" > <linearlayout android:la
            Yout_width= "Fill_parent" android:layout_height= "fill_parent" android:orientation= "vertical" > <button android:id= "@+id/doget" android:layout_width= "Fill_paren T "android:layout_height=" wrap_content "android:padding=" 10DP "Android:lay Out_marginbottom= "10DP" android:text= "Get Request" android:onclick= "DoClick"/&G
            T <button android:id= "@+id/dopost" android:layout_width= "Fill_parent" and Roid:layout_height= "Wrap_content" android:padding= "10DP" android:layout_marginbottom= "10DP"
                Android:text= "POST request" android:onclick= "DoClick"/> <button Android:id= "@+id/dophoto" android:layout_width= "Fill_parent" Android:layout_hei
                ght= "Wrap_content" android:padding= "10DP" android:layout_marginbottom= "10DP"
                android:text= "Photo" android:onclick= "Dophoto"/> <imageview Android:id= "@+id/showphoto" android:layout_width= "Fill_parent" android:layout_height= "250DP" android:scaletype= "Centercrop" android:src= "@drawable/add" Android
                : layout_marginbottom= "10DP"/> <textview android:id= "@+id/showcontent" Android:lAyout_width= "Fill_parent" android:layout_height= "Wrap_content" Android:layout_marginbottom = "10DP"/> </LinearLayout> </ScrollView> </LinearLayout>

Because I am not very familiar with Java, only read some video tutorials, actual development experience is not much, I wrote the comments according to their own understanding, but should not have any too big problem, if there are errors please point out, thank you.




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.