Android: Network Operations in android and android

Source: Internet
Author: User

Android: Network Operations in android and 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 <String, string> 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 <String, String> 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 <String, String> params, String enc) throws Exception {// username = jack & password = 123456 & age = 23 S TringBuilder sb = new StringBuilder (); if (params! = Null &&! Params. isEmpty () {for (Map. entry <String, String> 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 <String, String> 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 <String, String> 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 <String, String> params, String enc) throws Exception {List <NameValuePair> paramPairs = new ArrayList <NameValuePair> (); if (params! = Null &&! Params. isEmpty () {for (Map. entry <String, String> 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 contains the information of the uploaded file. * The data is submitted directly to the server over HTTP. the following form submission function is implemented: * <form method = post action = "http: // 192.168.0.200: 8080/ssi/fileload/test. do "enctype =" multipart/form-data "> <input type =" text "NAME =" name "> <input type =" text "NAME =" id "> <input type = "file" name = "imagefile"/> <input type = "file" name = "zip"/> </FORM> * @ param path upload path (note: avoid using a path like localhost or 127.0.0.1 as it will point to the phone simulator you can use http://www.itcast.cn or http: // 19 * @ Param params the request parameter key is the parameter name, and the value is the parameter value * @ param file to upload the file */public static boolean sendPostRequest (String path, map <String, String> 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 number of file types Total Data Length: StringBuilder fileExplain = new StringBuilder (); fileExplain. append ("--"); fileExplain. append (BOUNDARY); fileExplain. append ("\ r \ n"); fileExplain. append ("Content-Disposition: form-data; name = \" "+ uploadFile. getParameterName () + "\"; filename = \ "" + uploadFile. getFilname () + "\" \ r \ n "); fileExplain. append ("Content-Type:" + uploadFile. getContentType () + "\ r \ n"); fileExplain. append ("\ r \ n"); fileDataL Ength + = fileExplain. length (); if (uploadFile. getInStream ()! = Null) {fileDataLength + = uploadFile. getFile (). length ();} else {fileDataLength + = uploadFile. getData (). length ;}} StringBuilder textEntity = new StringBuilder (); for (Map. entry <String, String> 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 \ 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 (). length; 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 !!


How to implement a simple network connection application in Android

Note: To perform the network operations described in this lesson, the manifest file of your application must contain the following permissions: 1 2 <uses-permissionandroid: name = "android. permission. INTERNET "/> <uses-permissionandroid: name =" android. permission. ACCESS_NETWORK_STATE "/> select an HTTP Client Choose an HTTP Client. Most Android apps connected to the network use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HttpClient, which support HTTPS, stream upload and download,
Configurable timeout, IPv6, and connection pool. We recommend that you use HttpURLConnection in android applications whose version is "ginger pie" (android2.3) or later,

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.