Android apps to get photo paths after taking photos and uploading instances sharing _android

Source: Internet
Author: User
Tags event listener getmessage http post

The code in the activity, I only post important part of the event code

public void Dophoto (view view) {Destorybimap (); 
  String state = Environment.getexternalstoragestate (); 
    if (State.equals (environment.media_mounted)) {Intent Intent = new Intent ("Android.media.action.IMAGE_CAPTURE"); 
  Startactivityforresult (Intent, 1); 
  else {toast.maketext (mainactivity.this, "No SD card", Toast.length_long). Show (); } @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {URI uri = data.getd 
  ATA (); 
  if (URI!= null) {This.photo = Bitmapfactory.decodefile (Uri.getpath ()); 
    } if (This.photo = = null) {Bundle Bundle = Data.getextras (); 
    if (bundle!= null) {This.photo = (Bitmap) bundle.get ("Data"); 
      else {toast.maketext (mainactivity.this, "Photo failed", Toast.length_long). Show (); 
    Return 
  } FileOutputStream fileoutputstream = null; 
 try {//Get SD card root String savedir = environment.getexternalstoragedirectory () + "/meitian_photos";   New directory file DIR = new file (Savedir); 
    if (! dir.exists ()) Dir.mkdir (); 
    Generate filename SimpleDateFormat t = new SimpleDateFormat ("Yyyymmddsssss"); 
    String filename = "MT" + (T.format (new Date ()) + ". jpg"; 
    Creates a new file (Savedir, filename); 
    Open file output stream fileoutputstream = new FileOutputStream (file); 
    Generate Picture Files this.photo.compress (Bitmap.CompressFormat.JPEG, FileOutputStream); 
    The full path of the photo This.picpath = File.getpath (); 
    ImageView ImageView = (imageview) Findviewbyid (R.id.showphoto); 
  Imageview.setimagebitmap (This.photo); 
  catch (Exception e) {e.printstacktrace (); 
      finally {if (FileOutputStream!= null) {try {fileoutputstream.close (); 
      catch (Exception e) {e.printstacktrace (); /** * Destroy picture file/private void Destorybimap () {if (Photo!= null &&! photo.isrecycled 
    ()) {photo.recycle (); 
photo = null;  } 
} 

 

Layout Layout Page

<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_p" 
        Arent "android:layout_height=" fill_parent "android:orientation=" vertical "> <button 
        Android:id= "@+id/dophoto" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:padding= "10DP" android:layout_marginbottom= "10DP" android:text= "Photo" Android:onc lick= "Dophoto"/> <textview android:id= "@+id/showcontent" fi 
      Ll_parent "android:layout_height=" wrap_content "android:layout_marginbottom=" 10DP "/> <imageview AndrOid:id= "@+id/showphoto" android:layout_width= "fill_parent" android:layout_height= "250DP" Androi 
    D:scaletype= "Centercrop" android:src= "@drawable/add" android:layout_marginbottom= "10DP"/> 

 </LinearLayout> </ScrollView> </LinearLayout>

One of the Upload tool classes we look below together:
Android sends HTTP GET POST requests and uploads files via Multipartentitybuilder

All use the new way multipartentitybuilder to deal with.
Httpmime-4.3.2.jar
Httpcore-4.3.1.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

Directly on the code:
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.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.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"; /** * The current request URL */protected String URL = ""; 
 
  /** * The type of HTTP request * * protected String requsettype = Http_get; 
 
  /** * Timeout for connection request * * Protected int connectiontimeout = 5000; 
 
  /** * Timeout time for reading remote data */protected int sotimeout = 10000; 
 
  /** * Service-side Return status code */protected int statusCode =-1; /** * Current link character encoding/protected String charset = HTTP. 
 
  Utf_8; 
 
  /** * HTTP GET request Manager */protected httprequestbase httprequest= null; 
 
  /** * HTTP Request Configuration Parameters */protected httpparams httpparameters= null; 
 
  /** * HTTP Request Response * * protected httpresponse httpresponse= null; 
 
  /** * HTTP Client Connection Manager/protected httpclient httpclient= null; 
 
  /** * HTTP POST method to send multiple segment Data Manager/protected multipartentitybuilder multipartentitybuilder= null; 
 
  /** * Bind HTTP Request Event Listener/protected Onhttprequestlistener onhttprequestlistener = null; Public zhttprequest () {} public zhttprequest (onhttpRequestlistener listener) {This.setonhttprequestlistener (listener); 
    /** * Set the current request link * * @param URL * @return/public zhttprequest seturl (String URL) { 
    This.url = URL; 
  return this; /** * Set Connection Timeout * * @param timeout Unit (milliseconds), default 5000 * * @return/public zhttprequest SetConnect 
    Iontimeout (int timeout) {this.connectiontimeout = timeout; 
  return this; /** * Set the socket read Timeout * * @param timeout Unit (milliseconds), default 10000 * * @return/Public zhttprequest s 
    Etsotimeout (int timeout) {this.sotimeout = timeout; 
  return this; /** * Sets the encoding format for the contents * * @param charset default is UTF-8 * * @return * * Public zhttprequest Setcharset (S 
    Tring CharSet) {this.charset = charset; 
  return this; /** * Gets the type of the current HTTP request * * @return/public String Getrequesttype () {return this.requse 
  Ttype; }/** * Determines whether the currentHTTP GET Request * * @return/public boolean isget () {return this.requsettype = = Http_get; /** * To determine whether the current HTTP POST request * * @return/public boolean isPost () {return this.requsetty 
  PE = = Http_post; /** * Obtain HTTP Request response Information * * @return/public HttpResponse Gethttpresponse () {return this. 
  HttpResponse; /** * Get HTTP Client Connection Manager * * @return/public httpclient gethttpclient () {return this.ht 
  Tpclient; /** * Add header information for an HTTP request * * @param name * @param value * @return/Public Zhttpre 
    Quest AddHeader (string name, String value) {This.httpRequest.addHeader (name, value); 
  return this; /** * Obtain HTTP Get controller * * @return/public HttpGet Gethttpget () {return (HttpGet) 
  . HttpRequest; /** * Get HTTP POST Controller * * @return/public httppost gethttppost () 
  {return (httppost) this.httprequest; 
  /** * Get the requested status code * * @return * * * public int Getstatuscode () {return this.statuscode; /** * Request data by Get method * * @param URL * @return * @throws ioexception/public String get ( 
    String URL) throws Exception {this.requsettype = Http_get; 
    Sets the link this.seturl (URL) of the current request; 
    New HTTP GET Request This.httprequest = new HttpGet (This.url); 
    Execute client request This.httpclientexecute (); 
  Listens for service-side response events and returns the server-side content return This.checkstatus (); /** * Get HTTP POST multi-segment Data Submission Manager * * @return/public Multipartentitybuilder Getmultipartentitybuil Der () {if (This.multipartentitybuilder = null) {This.multipartentitybuilder = Multipartentitybuilder.cre 
      Ate (); 
      Set to Browser compatible mode Multipartentitybuilder.setmode (httpmultipartmode.browser_compatible); Sets the encoding format of the request Multipartentitybuilder.setcharset (charset.forName (This.charset)); 
  return this.multipartentitybuilder; 
    /** * After configuring the data to post submitted, execute the method to generate the data entity waiting to send/public void buildpostentity () {//Generate HTTP POST entity 
    Httpentity httpentity = This.multipartEntityBuilder.build (); 
  This.gethttppost (). setentity (httpentity); /** * Send POST request * * @param URL * @return * @throws Exception/public String POST (stri 
    ng URL) throws Exception {this.requsettype = Http_post; 
    Sets the link this.seturl (URL) of the current request; 
    New HTTP POST Request This.httprequest = new HttpPost (This.url); 
    Execute client request This.httpclientexecute (); 
  Listens for service-side response events and returns the server-side content return This.checkstatus (); 
  /** * Execute HTTP Request * * @throws Exception * * protected void Httpclientexecute () throws Exception 
    {//configure HTTP request Parameter this.httpparameters = new Basichttpparams (); 
    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); 
    Open a client HTTP request This.httpclient = new Defaulthttpclient (this.httpparameters); 
    Initiates an HTTP POST request before the execution of an event listener callback operation (e.g., custom submitted data fields or uploaded files, etc.) This.getonhttprequestlistener (). ONrequest (this); 
    Sends an HTTP request and gets the server-side response Status This.httpresponse = This.httpClient.execute (this.httprequest); 
  Gets the status code returned by the request This.statuscode = This.httpResponse.getStatusLine (). Getstatuscode (); /** * reads the input stream returned by the server and converts it to a string return * * @throws Exception/public string getInputStream () throws Except 
    Ion {//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); 
    ///Data received exit Instream.close (); 
  Convert data to string save return new String (Baos.tobytearray (), this.charset); /** * Close Connection Manager release resource/protected void Shutdownhttpclient () {if (this.httpclient!= null &&amp ; 
    This.httpClient.getConnectionManager ()!= null) {This.httpClient.getConnectionManager (). Shutdown (); }/** * listens for service-side response 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) {//request succeeded, Callback listener Event content = Listener.onsucceed (This.statuscode, Thi 
    s); 
    else {//request failed or other, callback listener event content = listener.onfailed (This.statuscode, this); 
    //Close Connection Manager release resource This.shutdownhttpclient (); 
  return content; /** * Event listener on HTTP request operation/public interface ONhttprequestlistener {/** * Initialize header information configuration or other data configuration prior to HTTP get or POST request * * @param reques 
 
    T * @throws Exception */public void ONrequest (Zhttprequest request) throws Exception; /** * Callback method when HTTP request response succeeds * * @param statusCode Current Status code * @param request * @return returns the requested string 
 
    Capacity * @throws Exception/public String onsucceed (int statusCode, zhttprequest request) throws Exception; /** * Callback method when HTTP request response fails * * @param statusCode Current Status code * @param request * @return return requests Failed hint content * @throws Exception/public String onfailed (int statusCode, zhttprequest request) throws Except 
  Ion /** * Binding HTTP Request Listener Event * * @param listener * @return/public zhttprequest Setonhttprequestl 
    Istener (Onhttprequestlistener listener) {This.onhttprequestlistener = listener; 
  return this; 
 /** * Gets the HTTP request listener event that has been bound  * * @return/public Onhttprequestlistener Getonhttprequestlistener () {return this.onhttprequestlis 
  Tener; 
 } 
}

How to use in activity (I'm still writing the body part code here):
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 (zhttpreq Uest request) throws Exception {} @Override public String onsucceed (int statusCode, zhttprequest reque 
    ST) 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 ContentType Text_plain = Contenttype.create ("Text/plain", ChArset.forname (CHARSET)); @Override public void ONrequest (Zhttprequest request) throws Exception {//Set header information for sending requests REQUEST.A 
      Ddheader ("Cookie", "abc=123;456= love is Happiness;"); 
      Configure the data to POST multipartentitybuilder builder = Request.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 req 
    Uest.getinputstream (); @Override public String onfailed (int statusCode, zhttprequest request) throws Exception {return "POS 
    T 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; 
  The catch (IOException e) {content = "IO exception:" + E.getmessage (); 
  catch (Exception e) {content = "Exception:" + E.getmessage (); 
} textview.settext (content); 
 }

Where Picpath is the type of picture path String in the SD card, I am the
Layout page
Activity_main.xml

for uploading directly after taking photos

<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_p" 
        Arent "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:on click= "DoClick"/> <button android:id= "@+id/dopost" android:layout_width= Ent "android:layout_height=" wrap_content "android:padding=" 10DP "android:layout_marginbottom=" 1 0DP "android:text="Post request "android:onclick=" DoClick "/> <button android:id=" @+id/dophoto " Droid:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:padding= "10DP" an Droid:layout_marginbottom= "10DP" android:text= "photographed" android:onclick= "Dophoto"/> <t Extview android:id= "@+id/showcontent" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_marginbottom= "10DP"/> <imageview android:id= "@+id/s" Howphoto "android:layout_width=" fill_parent "android:layout_height=" 250DP "android:scaletype=" C Entercrop "android:src=" @drawable/add "android:layout_marginbottom=" 10DP "/> </linea 

 Rlayout> </ScrollView> </LinearLayout>

As for the server I used PHP, just a simple output to get the data just

<?php 
Echo ' 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.