Android sends an http get post request and uploads a file through MultipartEntityBuilder (2

Source: Internet
Author: User

Android sends an http get post request and uploads the second version of a file through MultipartEntityBuilder

The code with the same function was roughly written last time. This time, some previous bugs have been fixed and the structure has been greatly modified. Now the application is more convenient.

Http://blog.csdn.net/zhouzme/article/details/18940279


Code directly:

ZHttpRequset. 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. mime. httpMultipartMode; import org. apache. http. entity. mi Me. 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. IOException; import java. io. inputStream; import java. nio. charset. charset;/*** Created by ZHOUZ On 14-2-3. */public class ZHttpRequest {public final String HTTP_GET = "GET"; public final String HTTP_POST = "POST "; /*** current request URL */protected String url = "";/*** HTTP request type */protected String requsetType = HTTP_GET; /*** connection request timeout time */protected int connectionTimeout = 5000;/*** timeout time for reading Remote Data */protected int soTimeout = 10000; /*** status code returned by the server */protected int statusCode =-1;/*** the word of the current link Character encoding */protected String charset = HTTP. UTF_8;/*** http get request manager */protected HttpRequestBase httpRequest = null;/*** HTTP request configuration parameter */protected HttpParams httpParameters = null; /*** HTTP request response */protected HttpResponse httpResponse = null;/*** HTTP client Connection Manager */protected HttpClient httpClient = null; /*** send multi-segment Data Manager via http post */protected MultipartEntityBuilder multipartEntityBuilder = null ;/* ** Bind the HTTP request event listener */protected OnHttpRequestListener onHttpRequestListener = null; public ZHttpRequest () {} public ZHttpRequest (OnHttpRequestListener listener) {this. setOnHttpRequestListener (listener);}/*** set the link ** @ param url * @ return */public ZHttpRequest setUrl (String url) {this. url = url; return this;}/*** sets the connection timeout time ** @ param timeout in milliseconds. The default value is 5000 * @ return */public ZHttpReq. Uest setConnectionTimeout (int timeout) {this. connectionTimeout = timeout; return this;}/*** set the socket read timeout time ** @ param timeout unit (MS ), 10000 * @ return */public ZHttpRequest setSoTimeout (int timeout) {this. soTimeout = timeout; return this;}/*** set the encoding format for the retrieved content ** @ param charset the default is UTF-8 * @ return */public ZHttpRequest setCharset (String charset) {this. charset = charset; return this ;}/* ** Obtain the type of the current HTTP request ** @ return */public String getRequestType () {return this. requsetType;}/*** determines whether the current http get request is ** @ return */public boolean isGet () {return this. requsetType = HTTP_GET;}/*** determine whether the current http post request is ** @ return */public boolean isPost () {return this. requsetType = HTTP_POST;}/*** get http Request Response Information ** @ return */public HttpResponse getHttpResponse () {return this. httpRe Response se;}/*** get http client Connection Manager ** @ return */public HttpClient getHttpClient () {return this. httpClient;}/*** Add the header information of an HTTP request ** @ param name * @ param value * @ return */public ZHttpRequest addHeader (String name, String value) {this. httpRequest. addHeader (name, value); return this;}/*** get http get controller ** @ return */public HttpGet getHttpGet () {return (HttpGet) this. httpRequest; }/*** Get the http post controller ** @ return */public HttpPost getHttpPost () {return (HttpPost) this. httpRequest;}/*** get the Request status code ** @ return */public int getStatusCode () {return this. statusCode;}/*** request data through GET ** @ param url * @ return * @ throws IOException */public String get (String url) throws Exception {this. requsetType = HTTP_GET; // set the current request link this. setUrl (url); // create an http get request this. ht TpRequest = new HttpGet (this. url); // execute the client request this. httpClientExecute (); // listen to the server's response to the event and return the server's content return this. checkStatus ();}/*** get http post multipart data submission manager ** @ return */public MultipartEntityBuilder getMultipartEntityBuilder () {if (this. multipartEntityBuilder = null) {this. multipartEntityBuilder = MultipartEntityBuilder. create (); // set it to the browser compatibility mode multipartEntityBuilder. setMode (HttpMultipartMode. BROWS ER_COMPATIBLE); // sets the Request Encoding format multipartEntityBuilder. setCharset (Charset. forName (this. charset);} return this. multipartEntityBuilder;}/*** After configuring the data to be submitted by POST, execute this method to generate the data entity waiting for sending */public void buildPostEntity () {// generate the http post object HttpEntity httpEntity = this. multipartEntityBuilder. build (); this. getHttpPost (). setEntity (httpEntity);}/*** send POST request ** @ param url * @ return * @ throws Exception */p Ublic String post (String url) throws Exception {this. requsetType = HTTP_POST; // set the current request link this. setUrl (url); // create an http post request this. httpRequest = new HttpPost (this. url); // execute the client request this. httpClientExecute (); // listen to the server's response to the event and return the server's content return this. checkStatus ();}/*** execute HTTP request ** @ throws Exception */protected void httpClientExecute () throws Exception {// configure the HTTP request parameter this. httpParameters = new Bas IcHttpParams (); this. httpParameters. setParameter ("charset", this. charset); // set the connection request timeout value HttpConnectionParams. setConnectionTimeout (this. httpParameters, this. connectionTimeout); // sets the socket read timeout value. setSoTimeout (this. httpParameters, this. soTimeout); // enable a client HTTP request this. httpClient = new DefaultHttpClient (this. httpParameters); // initiate the event listening callback operation before the http post request is executed (for example, custom submitted data fields or uploaded files) Files) this. getOnHttpRequestListener (). onRequest (this); // send an HTTP request and obtain the server response status. this. httpResponse = this.httpClient.exe cute (this. httpRequest); // gets the status code returned by the request. this. statusCode = this. httpResponse. getStatusLine (). getStatusCode ();}/*** read the input stream returned by the server and convert it to a String to return ** @ throws Exception */public String getInputStream () throws Exception {// receives the remote input stream InputStream inStream = this. httpResponse. getEntity (). getConten T (); // read the 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);} // exit inStream after data is received. close (); // convert the data into a String and save return new String (baos. toByteArray (), this. charset);}/*** close the Connection Manager to release resources */protected void shutdownHttpClient () {if (this. httpClient! = Null & this. httpClient. getConnectionManager ()! = Null) {this. httpClient. getConnectionManager (). shutdown () ;}/ *** listens to server-side events and returns server-side content ** @ return * @ throws Exception */protected String checkStatus () throws Exception {OnHttpRequestListener listener = this. getOnHttpRequestListener (); String content; if (this. statusCode = HttpStatus. SC _ OK) {// The request is successful. The callback listener event content = listener. onSucceed (this. statusCode, this);} else {// request failed or other, callback listener event content = listener. onFailed (this. statusCode, this);} // close the Connection Manager to release the resource this. shutdownHttpClient (); return content ;} /*** event listening interface during HTTP request operation */public interface OnHttpRequestListener {/*** initialize http get or POST request header information configuration or other data configuration operations * * @ param request * @ throws Exception */public void onRequest (ZHttpRequest request) throws Exception; /*** callback method when the HTTP request response is successful ** @ param statusCode Current Status Code * @ param request * @ return returns the string content of the request * @ throws Exception */ public String onSucceed (int statusCode, ZHttpRequest request) throws Exception; /*** callback method when the HTTP request response fails ** @ param statusCode Current Status Code * @ param request * @ return returns the request failure message * @ throws Exception */ public String onFailed (int statusCode, ZHttpRequest request) throws Exception;}/*** listener events bound to HTTP requests ** @ param listener * @ return */public ZHttpRequest setOnHttpRequestListener (OnHttpRequestListener listener) {this. onHttpRequestListener = listener; return this;}/*** get the bound HTTP request listening event ** @ return */public OnHttpRequestListener getOnHttpRequestListener () {return this. onHttpRequestListener ;}}

Usage in the Activity (here I still write only part of the body code ):

MainActivity. java

Public void doClick (View view) {ZHttpRequest get = new ZHttpRequest (); get. setCharset (HTTP. UTF_8 ). setConnectionTimeout (5000 ). setSoTimeout (5000); get. setOnHttpRequestListener (new ZHttpRequest. onHttpRequestListener () {@ Override public void onRequest (ZHttpRequest request) throws Exception {}@ Override public String onSucceed (int statusCode, ZHttpRequest request) throws Exception {return request. GetInputStream () ;}@ Override public String onFailed (int statusCode, ZHttpRequest request) throws Exception {return "GET request failed: statusCode" + statusCode ;}}); ZHttpRequest post = new ZHttpRequest (); post. setCharset (HTTP. UTF_8 ). setConnectionTimeout (5000 ). setSoTimeout (10000); post. setOnHttpRequestListener (new ZHttpRequest. onHttpRequestListener () {private String CHARSET = HTTP. UTF_8; private Con TentType TEXT_PLAIN = ContentType. create ("text/plain", Charset. forName (CHARSET); @ Override public void onRequest (ZHttpRequest request) throws Exception {// sets the request header information request. addHeader ("cookie", "abc = 123; 456 = love is happiness;"); // configure MultipartEntityBuilder = request for POST data. getMultipartEntityBuilder (); builder. addTextBody ("p1", "abc"); builder. addTextBody ("p2", "Chinese", TEXT_PLAIN); builder. AddTextBody ("p3", "abc Chinese CBA", TEXT_PLAIN); if (picPath! = Null &&! "". Equals (picPath) {builder. addTextBody ("pic", picPath); builder. addBinaryBody ("file", new File (picPath);} request. buildPostEntity () ;}@ Override public String onSucceed (int statusCode, ZHttpRequest request) throws Exception {return request. getInputStream () ;}@ Override public String onFailed (int statusCode, ZHttpRequest request) throws Exception {return "POST request failed: statusCode" + statusCode; }); TextView textView = (TextView) findViewById (R. id. showContent); String content = "initial content"; try {if (view. getId () = R. id. doGet) {content = get. get ("http://www.baidu.com"); content = "GET data: isGet:" + (get. isGet ()? "Yes": "no") + "=>" + content;} else {content = post. post ("http: // 192.168.1.6/test. php "); content =" POST Data: isPost "+ (post. isPost ()? "Yes": "no") + "=>" + content ;}} catch (IOException e) {content = "IO exception:" + e. getMessage ();} catch (Exception e) {content = "Exception:" + e. getMessage ();} textView. setText (content );}

Here, picPath is the String type of the image path in the SD card. It is used for uploading after taking a picture directly.

Code for photo display and upload part: http://blog.csdn.net/zhouzme/article/details/18952201


Layout page

Activity_main.xml

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical"> <ScrollView android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <LinearLayout android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical"> <Button android: id = "@ + id/doGet" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: padding = "10dp" android: layout_marginBottom = "10dp" android: text = "GET request" android: onClick = "doClick"/> <Button android: id = "@ + id/doPost" android: layout_width = "fill_parent" android: 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_height = "wrap_content" android: padding = "10dp" android: layout_marginBottom = "10dp" android: text = "" android: onClick = "doPhoto"/> <TextView android: id = "@ + id/showContent" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_marginBottom = "10dp"/> <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"/> </LinearLayout> </ScrollView> </LinearLayout>

As for the php I used on the server, I simply output the obtained data.

<?phpecho 'GET:<br>'. "\n";//print_r(array_map('urldecode', $_GET));print_r($_GET);echo '<br>'. "\n". 'POST:<br>'. "\n";//print_r(array_map('urldecode', $_POST));print_r($_POST);echo '<br>'. "\n". 'FILES:<br>'. "\n";print_r($_FILES);echo '<br>'. "\n". 'COOKIES:<br>'. "\n";print_r($_COOKIE);



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.