Android travel 15 network operations in android

Source: Internet
Author: User

Android travel 15 network operations in android

There is no difference between network operations in android and java. Many network operation methods in java can be moved to android for use. The main points are as follows:

1. Differences between post and get requests. You can refer to relevant information on the Internet for details. get is mainly used to splice string parameters into the address and send them to the server. The length is limited, in addition, the request parameters are exposed in the address bar, which is not very secure; post is mainly used to convert the request parameters to the corresponding http Request body and send them to the server. Compared with the get method, there is no limit on the parameter length, parameter information is not exposed to users;

2. in java web, we use a browser to send data in post mode. The browser helps us to convert the data to the corresponding http protocol. That is to say, the browser helps us set the data to the corresponding http Request body, then it is sent to the server. The user sends data to the server through the browser --> converts the browser to http --> sends data to the server. If we use android as the client to write post requests using java code, you need to set the Request body, while the get request only needs to splice the corresponding parameter address, the user sends data to the server through the android client --> encoding is set to the corresponding http protocol --> send to the server;

3. android contains the httpclient of apache, which is equivalent to the browser in the web. We can also use its api to perform corresponding request operations. Compared with pure java code, it encapsulates a lot of things, and we only need to select the corresponding api according to business needs. If we use apache httpclient in swing, We need to import the corresponding jar package.

Post request:

Java web: the user sends data to the server through a browser --> converts the browser to http --> sends data to the server

Java code: the user sends data to the server through the android client --> encoding is set to the corresponding http protocol --> send to the server

Httpclient: the user sends data to the server through the android client (httpclient helps us to convert it to the corresponding http protocol) --> send to the server

Code implementation function: there are corresponding annotations in it. In my project, I created a class dedicated to Http upload and download: HttpUtil

1. Obtain binary data, images, and videos from the server:

/*** Obtain binary data from the server, such as instance slices and videos * @ param serverUrl: server address * @ param newFileName: Address of the new file after obtaining the local file + name for example: c: // test.png */public static void getByteFromServer (String serverUrl, String newFileName) throws Exception {URL url = new URL (serverUrl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); // request conn in Get mode. setConnectTimeout (5*1000); // sets the connection latency. Because the memory of the android system is limited, you cannot establish a connection with the server for a long time. InputStream inStream = conn. getInputStream (); // obtain the Image data byte [] data = readInputStream (inStream) through the input stream; // obtain the image's binary data File imageFile = new File (newFileName ); fileOutputStream outStream = new FileOutputStream (imageFile); outStream. write (data); outStream. close ();}

/*** Convert the input stream to byte data * @ param inStream * @ return * @ throws Exception */public static byte [] readInputStream (InputStream inStream) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = inStream. read (buffer ))! =-1) {outStream. write (buffer, 0, len);} inStream. close (); return outStream. toByteArray ();}

2. Obtain text information from the server, such as text, html, xml, json, and other data information

/*** Obtain text information from the server, such as html and xml * @ param serverUrl * @ return text String */public static String getTxtFromServer (String serverUrl) throws Exception {URL url = new URL (serverUrl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5*1000); InputStream inStream = conn. getInputStream (); // obtain the txt data byte [] data = readInputStream (inStream) through the input stream; // obtain the txt binary data String txt = new String (data ); return txt ;}

3. Send data information to the server in get Mode

/** The Get request method is to put parameters in the address and send them to the server * Send a Get request to the server * @ param path: Server Request address * @ param params: request Parameter * @ param enc: encoding * @ return true: Request successful false: request failed * @ throws Exception */public static boolean sendGetRequest (String path, Map
 
  
Params, String enc) throws Exception {StringBuilder sb = new StringBuilder (path );//? Username = jack & password = 123456 & age = 23if (params! = Null &&! Params. isEmpty () {sb. append ('? '); For (Map. Entry
  
   
Entry: params. entrySet () {sb. append (entry. getKey ()). append ('= '). append (URLEncoder. encode (entry. getValue (), enc )). append ('&');} sb. deleteCharAt (sb. length ()-1);} URL url = new URL (sb. toString (); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5*1000); if (conn. getResponseCode () = 200) {// The request is successful. You can call the getByteFromServer method above to obtain the corresponding server data // byte [] B = readInputStream (conn. getInputStream (); return true;} return false ;}
  
 

4. Send data information to the server in post mode:

/** The Post request is converted to the corresponding http protocol in the browser * and the converted http protocol contains information such as Content-Type and Content-Length *. the client needs to set the post request to be sent out of the corresponding http protocol * send a post form request to the server * @ param path: server address * @ param params: Request Parameter * @ param enc: encoding * @ return true: Request successful false: request failed * @ throws Exception */public static boolean sendPostRequest (String path, map
 
  
Params, String enc) throws Exception {// username = jack & password = 123456 & age = 23 StringBuilder sb = new StringBuilder (); if (params! = Null &&! Params. isEmpty () {for (Map. Entry
  
   
Entry: params. entrySet () {sb. append (entry. getKey ()). append ('= '). append (URLEncoder. encode (entry. getValue (), enc )). append ('&');} sb. deleteCharAt (sb. length ()-1);} byte [] entitydata = sb. toString (). getBytes (); // get the binary data URL of the object = new url (path); HttpURLConnection conn = (HttpURLConnection) URL. openConnection (); conn. setRequestMethod ("POST"); conn. setConnectTimeout (5*1000); conn. setUseCaches (false); // do not cache conn. setDoOutput (true); // if data is submitted through post, you must set to allow external data output. // set the http request header to send a post request to the server, the Content-Type and Content-Length parameters are required. For other parameters, the Content Type can be omitted. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // you can specify the length of the Content to be sent. setRequestProperty ("Content-Length", String. valueOf (entitydata. length); conn. setRequestProperty ("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml + xml, application/vnd. ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd. ms-excel, application/vnd. ms-powerpoint, application/msword, */* "); conn. setRequestProperty ("Accept-Language", "zh-CN"); conn. setRequestProperty ("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0 ;. net clr 1.1.4322 ;. net clr 2.0.50727 ;. net clr 3.0.04506.30 ;. net clr 3.0.20.6.2152 ;. net clr 3.5.30729) "); conn. setRequestProperty ("Connection", "Keep-Alive"); OutputStream outStream = conn. getOutputStream (); outStream. write (entitydata); outStream. flush (); outStream. close (); if (conn. getResponseCode () = 200) {// The request is successful. You can call the getByteFromServer method above to obtain the corresponding server data // byte [] B = readInputStream (conn. getInputStream (); return true;} return false ;}
  
 

5. Send xml data information to the server in post mode:

/*** Send xml data to the server * @ param path: server address * @ param xml: xml string information * @ param enc: encoding * @ return true: Successful request false: request failed * @ throws Exception */public static boolean sendPostXMLRequest (String path, String xml, String enc) throws Exception {byte [] data = xml. getBytes (); URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("POST"); conn. setConnectTimeout (5*1000); conn. setDoOutput (true); // if data is submitted through post, you must set to allow external output data. // set the sending content type to xml data conn. setRequestProperty ("Content-Type", "text/xml; charset =" + enc); // set the length of the sent Content conn. setRequestProperty ("Content-Length", String. valueOf (data. length); OutputStream outStream = conn. getOutputStream (); outStream. write (data); outStream. flush (); outStream. close (); if (conn. getResponseCode () = 200) {// byte [] B = readInputStream (conn. getInputStream (); return true;} return false ;}

6. Use HttpClient to send data to the server in get mode:

/*** Send a get request through httpClient * @ param path: server address * @ param params: parameter name * @ param enc: encoding * @ return true: Request success false: request failed * @ throws Exception */public static boolean sendGetRequestFromHttpClient (String path, Map
 
  
Params, String enc) throws Exception {StringBuilder sb = new StringBuilder (path );//? Username = jack & password = 123456 & age = 23if (params! = Null &&! Params. isEmpty () {sb. append ('? '); For (Map. Entry
  
   
Entry: params. entrySet () {sb. append (entry. getKey ()). append ('= '). append (URLEncoder. encode (entry. getValue (), enc )). append ('&');} sb. deleteCharAt (sb. length ()-1);} // equivalent to HttpClient httpClient = new DefaultHttpClient (); // get an HttpGet object HttpGet = new HttpGet (sb. toString (); // send a Get request HttpResponse response=httpClient.exe cute (get); if (response. getStatusLine (). getStatusCode () = 200) {// String str = EntityUtils. toString (response. getEntity (); to get the server data // InputStream inStream = httpEntity. getContent (); to get the server input stream return true;} return false ;}
  
 

7. Use HttpClient to send a post request to the server:

/*** Send a Post request through httpClient * @ param path: server address * @ param params: parameter name * @ param enc: encoding * @ return true: Request success false: request failed * @ throws Exception */public static boolean sendPostRequestFromHttpClient (String path, Map
 
  
Params, String enc) throws Exception {List
  
   
ParamPairs = new ArrayList
   
    
(); If (params! = Null &&! Params. isEmpty () {for (Map. Entry
    
     
Entry: params. entrySet () {paramPairs. add (new BasicNameValuePair (entry. getKey (), entry. getValue () ;}} UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity (paramPairs, enc); // get the encoded object data HttpPost post = new HttpPost (path ); // formpost. setEntity (entitydata); DefaultHttpClient client = new DefaultHttpClient (); // The HttpResponse response = client.exe cute (post) browser; // execute the request if (response. getStatusLine (). getStatusCode () = 200) {// String str = EntityUtils. toString (response. getEntity (); to get the server data // InputStream inStream = httpEntity. getContent (); to get the server input stream return true;} return false ;}
    
   
  
 

8. Sending the uploaded file information to the server through post is equivalent to submitting a web form. The form contains the uploaded file. In fact, it is converted to the corresponding http protocol at the underlying layer when the browser uploads a form, we can also write the corresponding request body and submit it to the server. It is easy to understand the principle;

Create a form object file:

Public class FormFile {/* Upload File data */private byte [] data; private InputStream inStream; private file File;/* file name */private String filname; /* request parameter name */private String parameterName;/* content type */private String contentType = "application/octet-stream"; public FormFile (String filname, byte [] data, string parameterName, String contentType) {this. data = data; this. filname = filname; this. parameterName = parameterN Ame; if (contentType! = Null) this. contentType = contentType;} public FormFile (String filname, File file, String parameterName, String contentType) {this. filname = filname; this. parameterName = parameterName; this. file = file; try {this. inStream = new FileInputStream (file);} catch (FileNotFoundException e) {e. printStackTrace ();} if (contentType! = Null) this. contentType = contentType;} public File getFile () {return file;} public InputStream getInStream () {return inStream;} public byte [] getData () {return data ;} public String getFilname () {return filname;} public void setFilname (String filname) {this. filname = filname;} public String getParameterName () {return parameterName;} public void setParameterName (String parameterName) {this. parameterName = parameterName;} public String getContentType () {return contentType;} public void setContentType (String contentType) {this. contentType = contentType ;}}

Send a request containing a File:

/*** The information submitted to the server includes the information of the uploaded file. * data is submitted directly to the server over HTTP. the following form submission function is implemented: ** @ param path: avoid using a path test like localhost or 127.0.0.1 because it will point to the phone simulator and you can use a path test like http://www.itcast.cn or http: // 192.168.1.10: 8080) * @ param params the request parameter key is the parameter name, and value is the parameter value * @ param file Upload file */public static boolean sendPostRequest (String path, Map
 
  
Params, FormFile [] files) throws Exception {final String BOUNDARY = "--------------------------- 7da1_7580612 "; // data separation line final String endline = "--" + BOUNDARY + "-- \ r \ n"; // data end mark int fileDataLength = 0; for (FormFile uploadFile: files) {// obtain the total length of the file type data StringBuilder fileExplain = new StringBuilder (); fileExplain. append ("--"); fileExplain. append (BOUNDARY); fileExplain. append ("\ r \ n"); fileExplain. appen D ("Content-Disposition: form-data; name = \" "+ uploadFile. getParameterName () + "\"; filename = \ "" + uploadFile. getFilname () + "\" \ r \ n "); fileExplain. append ("Content-Type:" + uploadFile. getContentType () + "\ r \ n"); fileExplain. append ("\ r \ n"); fileDataLength + = fileExplain. length (); if (uploadFile. getInStream ()! = Null) {fileDataLength + = uploadFile. getFile (). length ();} else {fileDataLength + = uploadFile. getData (). length ;}} StringBuilder textEntity = new StringBuilder (); for (Map. entry
  
   
Entry: params. entrySet () {// construct the object data textEntity of the text type parameter. append ("--"); textEntity. append (BOUNDARY); textEntity. append ("\ r \ n"); textEntity. append ("Content-Disposition: form-data; name = \" "+ entry. getKey () + "\" \ r \ n "); textEntity. append (entry. getValue (); textEntity. append ("\ r \ n");} // calculates the total length of the object data transmitted to the server. int dataLength = textEntity. toString (). getBytes (). length + fileDataLength + endline. getBytes (). len Response; URL url = new URL (path); int port = url. getPort () =-1? 80: url. getPort (); Socket socket = new Socket (InetAddress. getByName (url. getHost (), port); OutputStream outStream = socket. getOutputStream (); // The String requestmethod = "POST" + url sent in the HTTP request header is completed below. getPath () + "HTTP/1.1 \ r \ n"; outStream. write (requestmethod. getBytes (); String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml + xml, applica Tion/vnd. ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd. ms-excel, application/vnd. ms-powerpoint, application/msword, */* \ r \ n "; outStream. write (accept. getBytes (); String language = "Accept-Language: zh-CN \ r \ n"; outStream. write (language. getBytes (); String contenttype = "Content-Type: multipart/form-data; boundary =" + BOUNDARY + "\ r \ n"; outStream. write (contenttyp E. getBytes (); String contentlength = "Content-Length:" + dataLength + "\ r \ n"; outStream. write (contentlength. getBytes (); String alive = "Connection: Keep-Alive \ r \ n"; outStream. write (alive. getBytes (); String host = "Host:" + url. getHost () + ":" + port + "\ r \ n"; outStream. write (host. getBytes (); // After writing the HTTP Request Header, write another carriage return outStream Based on the HTTP protocol. write ("\ r \ n ". getBytes (); // send object data of all text types out of outStream. write (textEn Tity. toString (). getBytes (); // send object data of all file types out for (FormFile uploadFile: files) {StringBuilder fileEntity = new StringBuilder (); fileEntity. append ("--"); fileEntity. append (BOUNDARY); fileEntity. append ("\ r \ n"); fileEntity. append ("Content-Disposition: form-data; name = \" "+ uploadFile. getParameterName () + "\"; filename = \ "" + uploadFile. getFilname () + "\" \ r \ n "); fileEntity. append ("Content-Type:" + uploadFi Le. getContentType () + "\ r \ n"); outStream. write (fileEntity. toString (). getBytes (); if (uploadFile. getInStream ()! = Null) {byte [] buffer = new byte [1024]; int len = 0; while (len = uploadFile. getInStream (). read (buffer, 0, 1024 ))! =-1) {outStream. write (buffer, 0, len);} uploadFile. getInStream (). close ();} else {outStream. write (uploadFile. getData (), 0, uploadFile. getData (). length);} outStream. write ("\ r \ n ". getBytes ();} // The End mark of the sent data below, indicating that the data has ended outStream. write (endline. getBytes (); BufferedReader reader = new BufferedReader (new InputStreamReader (socket. getInputStream (); if (reader. readLine (). indexOf ("200") =-1) {// read the data returned by the web server and determine whether the request code is 200. If it is not 200, return false for request failure;} outStream. flush (); outStream. close (); reader. close (); socket. close (); return true ;}
  
 

You can copy the code and use it directly after you have mastered it !!

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.