Android to server get and post requests in two ways, Android sends files to the server, assembles its own protocol and uses third party open source

Source: Internet
Author: User
Tags getmessage file transfer protocol

Tag: Android post file    android send file    android get POST request to server     Android send picture    

/** * @author [email protected] * @time 20140606 * * Package Com.intbird.utils;import Java.io.bufferedreader;import Java.io.dataoutputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.IOException;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.URL;import Java.net.urlconnection;import Java.net.urldecoder;import Java.net.urlencoder;import Java.nio.charset.Charset; Import Java.util.arraylist;import java.util.hashmap;import Java.util.iterator;import Java.util.Map;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.entity.mime.multipartentity;import Org.apache.http.entity.mime.content.filebody;import Org.apache.http.entity.mime.content.stringbody;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.util.entityutils;import android.graphics.bItmap;import Android.graphics.bitmapfactory;import Android.os.handler;import Android.os.message;public class conninternet {/** * start connection */public static int http_status_start=0;/** * Connection process error */public static int http_status_error=400;/* * * Request succeeded, return data */public static int http_status_reultok=200;/** * Server not responding */public static int http_status_noresp=500;/** * Normal GET request * @param API * @param callBack */public static void Get1 (final String api,final conninternetcallback callBack) {FINA L Handler Handler=gethandle (API, CallBack); new Thread () {@Overridepublic void run () {Message msg=handler.obtainmessage ( Http_status_start, "Start connection"); try {URL url = new URL (API); HttpURLConnection urlconn = (httpurlconnection) url.openconnection (); int Rescode=urlconn.getresponsecode (); if ( Rescode!=http_status_reultok) {msg.what=http_status_noresp;msg.obj=rescode;handler.sendmessage (msg); return;} InputStreamReader instream=new InputStreamReader (Urlconn.getinputstream ()); BufferedReader buffer=new BufferedReader (instream); StringResult= ""; String Inputline=null;while ((Inputline=buffer.readline ())!=null) {result+=inputline;}    Msg.what=http_status_reultok;    Msg.obj=urldecoder.decode (Result, "UTF-8"); Instream.close (); Urlconn.disconnect ();}    catch (Exception ex) {msg.what=http_status_error; Msg.obj=ex.getmessage (). toString ();} Finally{handler.sendmessage (msg);}}. Start ();} public void Get3 (final String api,final Conninternetcallback callBack) {final Handler Handler=gethandle (API, CallBack); New Thread () {@Overridepublic void run () {Message msg=handler.obtainmessage (Http_status_start, "Start connection"); try {HttpGet Httpget=new HttpGet (API); HttpClient HttpClient = new Defaulthttpclient (); HttpResponse Httpresp = Httpclient.execute (httpget); int rescode=httpresp.getstatusline (). GetStatusCode (); if ( Rescode!=http_status_reultok) {msg.what=http_status_noresp;msg.obj=rescode;handler.sendmessage (msg); return;} msg.what=http_status_reultok;msg.obj= entityutils.tostring (Httpresp.getentity ());} catch (Exception e) {Msg.what=http_status_error; msg.obj= e.getmessage ();} Finally{handler.sendmessage (msg);}}. Start ();} private static Handler GetHandle (final String api,final conninternetcallback callBack) {return new Handler () {@ overridepublic void handlemessage (Message message) {//Do not write here!callback.callback (Message.what,api, Message.obj.toString ());}};} /** * Simple Type, only the post of the text message; * @param API API Address * @param params only field parameter * @param callBack return call; */public static void Post1 (final String api,final hashmap<string,string> params,final conninternetcallback CallBack) {final Handler Handler=gethandle (API, CallBack); new Thread () {@Overridepublic void run () {Message msg= Handler.obtainmessage (Http_status_start, "Start connection"); try {URL url=new url (API); HttpURLConnection urlconn = (httpurlconnection) url.openconnection (); Urlconn.setdoinput (true); UrlConn.setDoOutput ( true); Urlconn.setrequestmethod ("POST"); Urlconn.setusecaches (false); Urlconn.setinstancefollowredirects (true); Urlconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); URLCOnn.setrequestproperty ("Charset", "UTF-8"); Urlconn.connect ();              DataOutputStream out = new DataOutputStream (Urlconn.getoutputstream ());            Iterator<string> Iterator=params.keyset (). Iterator ();            while (Iterator.hasnext ()) {String key= iterator.next ();            String value= Urlencoder.encode (Params.get (key), "UTF-8");              Out.write ((key+ "=" +value+ "&"). GetBytes ());              } out.flush ();                      Out.close (); int Rescode=urlconn.getresponsecode (); if (Rescode!=http_status_reultok) {msg.what=http_status_noresp;msg.obj=            Rescode;handler.sendmessage (msg); return;}            String result= "";            String Readline=null;            InputStreamReader inputstream=new InputStreamReader (Urlconn.getinputstream ());            BufferedReader bufferreader=new BufferedReader (InputStream);            while ((Readline=bufferreader.readline ())!=null) {result+=readline; } msg.What=http_status_reultok;            Msg.obj=urldecoder.decode (Result, "UTF-8");            Inputstream.close ();            Bufferreader.close (); Urlconn.disconnect ();}    catch (Exception ex) {msg.what=http_status_error; Msg.obj=ex.getmessage (). toString () + ".";} finally{handler.sendmessage (msg);}}. Start ();} /** * Custom text and file Transfer Protocol [example at end of function]; * @param apiurl API Address * @param mapparams text field parameter * @param listupfiles multi-file parameter * @param callBack return call; */public static void Post2 (final String apiurl,final hashmap<string,string> mapparams,final arraylist< Conninternetuploadfile> Listupfiles,conninternetcallback callBack) {final Handler handler=gethandle (APIURL, CallBack); new Thread (New Runnable () {public void run () {Message msg=handler.obtainmessage (Http_status_start, "Start Connection"); String boundary= "——— 7d4a6454354fe54scd"; String prefix= "--"; String line_end= "\ r \ n"; Try{url url=new URL (Apiurl); HttpURLConnection urlconn= (httpurlconnection) url.openconnection (); Urlconn.setdooutput (true); UrlConn.Setdoinput (True); Urlconn.setusecaches (false); Urlconn.setrequestmethod ("POST"); Urlconn.setrequestproperty (" Connection "," keep-alive "), Urlconn.setrequestproperty (" Charset "," UTF-8 "); Urlconn.setrequestproperty (" Content-type "," Multipart/form-data; boundary= "+boundary);D ataoutputstream outstream=new DataOutputStream ( Urlconn.getoutputstream ()); for (map.entry<string,string> Entry:mapParams.entrySet ()) {StringBuilder sbparam= New StringBuilder (); Sbparam.append (PREFIX); sbparam.append (boundary); Sbparam.append (line_end); Sbparam.append (" Content-disposition:form-data;name=\ "" + entry.getkey () + "\" "+line_end) sbparam.append (" content-transfer-encoding : 8bit "+ line_end); Sbparam.append (line_end); Sbparam.append (Entry.getvalue ()); Sbparam.append (line_end); o Utstream.write (Sbparam.tostring (). GetBytes ());} for (Conninternetuploadfile file:listupfiles) {StringBuilder sbfile=new StringBuilder (); Sbfile.append (PREFIX); Sbfile.append (boundary); Sbfile.append (line_end); Sbfile.append ("Content-disposition:form-data;namE=\ "" +file.getformname () + "\"; filename=\ "" +file.getfilename () + "\" "+line_end) Sbfile.append (" Content-type: "+ File.getcontenttype () + "\" "+line_end"; Outstream.write (Sbfile.tostring (). GetBytes ()); Writefiletooutstream ( Outstream,file.getfileurl ()); Outstream.write (Line_end.getbytes ("UTF-8")); Byte[] End_data= (prefix+boundary+prefix+line_end) getBytes ("UTF-8"); Outstream.write (End_data); Outstream.flush ()          ; Outstream.close (); int Rescode=urlconn.getresponsecode (); if (Rescode!=http_status_reultok) {msg.what=http_status_noresp;msg.obj=            Rescode;handler.sendmessage (msg); return;}            String result= "";            String Readline=null;            InputStreamReader inputstream=new InputStreamReader (Urlconn.getinputstream ());            BufferedReader bufferreader=new BufferedReader (InputStream);            while ((Readline=bufferreader.readline ())!=null) {result+=readline;        } Msg.what=http_status_reultok;        Msg.obj=urldecoder.decode (Result, "UTF-8"); InchPutstream.close ();            Bufferreader.close (); Urlconn.disconnect ();}    catch (Exception ex) {msg.what=http_status_error; Msg.obj=ex.getmessage (). toString ();} finally{handler.sendmessage (msg);}}). Start ();//hashmap<string,string> params=new hashmap<string, string> ();//params.put ("pid", Filehelper.getshareprof ("PassportID"));//params.put ("JSON", Postjson (text));//arraylist<uploadfile> Uploadfiles=new arraylist<uploadfile> ();//if (Url.length () >0) {//uploadfile upfile=new UploadFile (Url,url, "Images");//uploadfiles.add (upfile);//}//internet.post (Api.api_messagecreate, params,uploadfiles,new Internetcallback () {//@Override//public void callBack (int msgwhat, string API, string result) {//if (msgwhat== INTERNET.HTTP_STATUS_OK) {////with new data//adapter.notifydatasetchanged ();////shows no data//}else showtoast ("network error");//}//});} /** * Third-party Apache integrated post * @param URL API address * @param mapparams parameter * @param callBack */public static void Post3 (Final String u RL, Final HASHMap<string,string> mapparams,final hashmap<string,string> mapfileinfo,conninternetcallback callBack) { Final Handler handler=gethandle (URL, callBack); new Thread () {@Overridepublic void run () {Message msg=        Handler.obtainmessage (Http_status_start, "Start connection"); try {httppost httppost = new HttpPost (URL); Multi-type;          Multipartentity multipartentity = new multipartentity ();        Field Iterator<?> It=mapparams.keyset (). Iterator ();        while (It.hasnext ()) {string key= (String) it.next ();    String Value=mapparams.get (key);        Multipartentity.addpart (Key,new stringbody (Value,charset.forname ("UTF-8"));        }//File It=mapfileinfo.keyset (). iterator ();        while (It.hasnext ()) {string key= (String) it.next ();        String Value=mapfileinfo.get (key);        Multipartentity.addpart (Key, new Filebody (value)); } httppost.setentity (multipartentity); HttpClient HttpClient = new Defaulthttpclient (); HttpResponse httPresp = Httpclient.execute (httppost); int rescode=httpresp.getstatusline (). Getstatuscode (); if (rescode!=http_status _reultok) {msg.what=http_status_noresp;msg.obj=rescode;handler.sendmessage (msg); return;} msg.what=http_status_reultok;msg.obj= entityutils.tostring (Httpresp.getentity ());} catch (Exception e) {msg.what=http_status_error;msg.obj= e.getmessage ();} Finally{handler.sendmessage (msg);}}. Start ();} public static Bitmap loadbitmapfromnet (String imgurl,bitmapfactory.options Options) {Bitmap Bitmap = null; URL ImageUrl = null;if (Imgurl = = NULL | | imgurl.length () = = 0) return null;try {imageUrl = new URL (Imgurl); URLConnection conn = Imageurl.openconnection (); Conn.setdoinput (true); Conn.connect (); InputStream is = Conn.getinputstream (); int length = Conn.getcontentlength (); if (length! =-1) {byte[] Imgdata = new byte[length];byte[] Tem p = new Byte[512];int Readlen = 0;int Destpos = 0;while ((Readlen = Is.read (temp))! =-1) {system.arraycopy (temp, 0, Imgda Ta, Destpos, Readlen);d Estpos + = Readlen;} Bitmap = Bitmapfactory.decodebytearray (imgdata, 0, imgdata.length,options); Options.injustdecodebounds=false;bitmap = Bitmapfactory.decodebytearray (imgdata, 0, imgdata.length,options);}} catch (IOException e) {return null;} return bitmap;} public static void Writefiletooutstream (DataOutputStream outstream,string url) {try {InputStream InputStream = new FileInputStream (new File (URL)), int ch;while ((Ch=inputstream.read ())!=-1) {outstream.write (ch);} Inputstream.close ();} catch (Exception e) {e.printstacktrace ();}} public interface conninternetcallback{public void callBack (int msgwhat,string api,string result); public class Conninternetuploadfile {private string Filename;private string Fileurl;private string formname;private String contentType = "Application/octet-stream";//image/jpegpublic conninternetuploadfile (string filename, string FILEURL, String formname) {this.filename = Filename;this.fileurl=fileurl;this.formname = FormName;} Public String Getfileurl () {return fileUrl;} public void SetfilEurl (String URL) {this.fileurl=url;} Public String GetFileName () {return filename;} public void Setfilename (String filename) {this.filename = filename;} Public String Getformname () {return formname;} public void Setformname (String formname) {this.formname = FormName;} Public String getContentType () {return contentType;} public void setContentType (String contentType) {this.contenttype = ContentType;}}}

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.