Android--http protocol

Source: Internet
Author: User

 1 package com.http.get; 2 3 Import Java.io.FileOutputStream; 4 Import java.io.IOException; 5 Import Java.io.InputStream; 6 Import java.net.HttpURLConnection; 7 Import java.net.MalformedURLException; 8 Import Java.net.URL;      9 public class Httputils {One private static String Url_path = "http://192.168.1.106:8080/green.jpg"; 12/**13 * @param args14 */15 public static void Main (string[] args) {16//call method get picture and save it Saveimagetodi         SK (); 18}19/**20 * Access pictures via Url_path's address and save to local */22 public static void Saveimagetodisk () 23 {24 InputStream inputstream= getInputStream (); byte[] data=new byte[1024];26 int len=0;27 File OutputStream fileoutputstream=null;28 try {29//To save the picture file in the local F-disk fileoutputstream=new Fileo Utputstream ("F:\\test.png"); (Len=inputstream.read (data)!=-1) 32 {33// To write a picture stream in a file FileOutputStream. write (Data,0,len);         }36} catch (IOException e) {PNS e.printstacktrace ();}39 finally40                     {41//Last Close stream if (inputstream!=null), {45                 Inputstream.close (); IOException} catch (e) {e.printstacktrace (); 48                     }49}50 if (fileoutputstream!=null) {53 Fileoutputstream.close (); IOException} catch (e) {e.printstacktrace (); 5 6}57}58}59}60/**61 * get pictures by URL * @return The input stream of the URL address picture. */64 public static InputStream getInputStream () {InputStream InputStream = null;66 HTTPURLC Onnection httpurlconnection = null;67-try {69//) instantiate a URL object based on the URL address for creating the HttpURLConnection object.    70         URL url = new URL (url_path); (URL! = null) {//openconnection Gets the connection to the current URL 74                 HttpURLConnection = (httpurlconnection) url.openconnection (); 75//Set 3-second response Timeout 76 Httpurlconnection.setconnecttimeout (3000); 77//Set allow input of httpurlconnection.setdoinput (tr UE); 79//Set to get method request data Httpurlconnection.setrequestmethod ("get"); 81//Get Connected The response code, 200 for the success, if for the other, are indicated to have the problem of the Responsecode=httpurlconnection.getresponsecode int (); onsecode==200) (//getinputstream) The data stream returned by the server is obtained. Inputstream=httpurlconnection.getinputstream (); 87}88}89 90} catch (Malformedurlexception e) {e.printstacktrace (); catch (IOException e) {E.P Rintstacktrace (); 94}95 return inputstream;96     }97 98} 


Post mode

This example accesses a login page via post, requiring a username (username) and password (password). Although the Java used here is explaining the problem, the server is used. NET Framework, a very simple HTML page plus a form to send the general handler, input for admin+123 for landing success, here not tired of.

Java code:

  1 package com.http.post;  2 3 Import Java.io.ByteArrayOutputStream;  4 Import java.io.IOException;  5 Import Java.io.InputStream;  6 Import Java.io.OutputStream;  7 Import java.io.UnsupportedEncodingException;  8 Import java.net.HttpURLConnection; 9 Import Java.net.URL; Ten import Java.net.URLEncoder; Import Java.util.HashMap; Import Java.util.Map; public class Postutils {p. private static String PATH = "Http://192.168.222.1:1231/loginas.ashx"; rivate static URL url;  Public Postutils () {$} static {$ try {% URL = new URL (PATH); 24} catch (Exception e) {e.printstacktrace (); 26} 27} 28 29/** 30 * via given request parameters and encoding Format, gets the data returned by the server * @param params request parameter * @param encode encoded format * @return the string received by * */Public static string Sendpostmessage (Map<string, string> params, string encode) {Notoginseng StringBuffer bu Ffer = New StringBuffer (); if (params = null &&!params.isempty ()) {map.entry<string, string> Entry:                             Params.entryset ()) {try {buffer.append (Entry.getkey ()) 42                             . Append ("=") Append (Urlencoder.encode (Entry.getvalue (), encode)) 44 . Append ("&");//Use & split between the requested parameters.                 (Unsupportedencodingexception e) {e.printstacktrace (); 47 } Buffer.deletecharat (Buffer.length ()-1); Wuyi System.out.println (buffer.tostring ());                         HttpURLConnection URLConnection = (httpurlconnection) URL 54 . OpenConnection (); Urlconnection.setconnecttimeout (3000); 56//Set allow input/output urlconnection.setdoinput (TRUE); The URlconnection.setdooutput (TRUE); byte[] MyData = buffer.tostring (). GetBytes ();                         60//Set Request packet header, set request data type Urlconnection.setrequestproperty ("Content-type", 62 "application/x-www-form-urlencoded");                         63//Set Request data length Urlconnection.setrequestproperty ("Content-length", 65 String.valueof (mydata.length)); 66//Set POST method request data Urlconnection.setrequestmethod ("POST"); OutputStream outputstream = Urlconnection.getoutputstream (); Outputstream.write (MyData); responsecode int = Urlconnection.getresponsecode (); if (Responsecode = =) {Changeinputstream return (urlconnection.getinputstream (), encode);            (IOException e) {e.printstacktrace (); 77 } ""; 80} 81 82/** 83 * Convert the input stream returned by the server into a string format. * @param the input streams returned by the InputStream servers. * @param encode encoding format 8             6 * @return Parsed string, */InputStream InputStream, 89 String encode) {Bytearrayoutputstream outputstream = new Bytearrayoutputstream (); byte[] data = n EW byte[1024]; an int len = 0; result= String "";  94 if (InputStream! = null) {up-try {(len = inputstream.read (data))! =-1)                     {Outputstream.write (Data,0,len);             98} result=new String (Outputstream.tobytearray (), encode); 100 101 } catch (IOException e) {102 e.printstacktrace (); 103}104}105 return R esult;106}107 108/**109 * @param args110 */111 public static void Main (string[] args) {112//sets the request string via map. 113 map<string, string> params = new hashmap<string, string> (), Params.put ("username", "adm        In "); Params.put (" Password "," 123 "); Result=sendpostmessage String (params, "utf-8"); 117 System.out.println (result); 118}119 120}

Android--http Protocol

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.