HttpURLConnection is a class provided by Java for Network access. Android Network access click to open link
Get request mode (implements the ability to download the appropriate file from the server):
public class Httpurlget {//httpurlconnection class get Server A picture public static void main (string[] args) {//TODO auto-generated Meth od stubtry {URL url = new URL ("Http://localhost:80/12.jpg"); HttpURLConnection Urlcon = (httpurlconnection) url.openconnection (); Urlcon.setreadtimeout (+); Set the connection server timeout time urlcon.setdoinput (true); Sets the read data from the server Urlcon.setdooutput (true); Set to send data to the server//httpurlconnection if the request method is not set, the default is GET request Urlcon.setrequestmethod ("POST");//urlcon.connect (); Nputstream input = Urlcon.getinputstream (); There is a connection function, can not write the above sentence FileOutputStream fs = new FileOutputStream (New File ("f:\\test.jpg")); byte[] B = new Byte[1024];while ( Input.read (b)!=-1) {fs.write (b);} System.out.println ("Download succeeded"); Fs.close (); Input.close (); Urlcon.disconnect ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Post request (the URL address designed below is the corresponding code on the local server and is written only for the implementation of the relevant feature)
public class Httpurlpost {public static void main (string[] args) {//TODO auto-generated method stubtry {URL url = new URL ("http://localhost/User/UserRegisterMobileNoIsExists"); HttpURLConnection Urlcon = (httpurlconnection) url.openconnection (); Urlcon.setreadtimeout (+); UrlCon.setDoInput ( true); Urlcon.setdooutput (true); Urlcon.setrequestmethod ("POST"); Urlcon.setdefaultusecaches (false); Urlcon.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); String param = "mobileno=13826040804&platform=android"; Urlcon.connect (); OutputStream OS = Urlcon.getoutputstream (); Os.write (Param.getbytes ()); int responsecode = Urlcon.getresponsecode (); BufferedReader br = null;if (Responsecode = =) {br = new BufferedReader (New InputStreamReader (Urlcon.getinputstream ()) ); String Str;while ((Str=br.readline ())!=null) {System.out.println (str);}} ELSE{SYSTEM.OUT.PRINTLN ("fail");} Br.close (); Os.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Network requests