Httpurlconnection_ Summary plus the small demo of the service side
I've got the following steps in building the Android connection to the server.
1. Create Child threads
Generally there is a lot of uncertainty about creating a connection with the server, so it's best to create a new subroutine to do this.
2, using the URL to encapsulate the access to the server address.
URL url = new URL ("http://10.0.2.2:1234") (Android emulator accesses proxy address for local 127.0.0.1)
3. Create an object to receive and send HTTP HttpURLConnection
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Note that this statement does not start with a server connection just a new object.
4. Set HTTP request header information
The new HttpURLConnection Connection object is designed to set the HTTP request headers, where we can use many methods like
Sets whether to write data to a connection (the post must be set) Getoutputstream ()
Conn.setdooutput (TRUE);
Whether the data can be read from the httpurlconnection default is True getInputStream
Conn.setdoinput (TRUE);
Post requests cannot be cached by using a cache Get request (URL)
Conn.setusecaches (FALSE);
Conn.setrequestproperty ("Content-type", "Application/json");
Conn.setrequestmethod ("POST");
Conn.setconnecttimeout (5000);//connection time is 5 seconds.
/
5, Establish connection connect ()
Generally use Connect () for the display of the network connection, it is worth emphasizing that the connection here does not involve HTTP header information, etc., connect () connection is the TCP connection is established three times handshake connection. There is no interface section to the application layer. So the backend interface does not receive the data (the body data part also does not send). The Connect () method is implicitly invoked by many other methods such as Getoutputstream ()/getresponsecode, and so on.
/
6, send the body part and receive the background returned data
Conn.getinputstream (), calling this function sends the HTTP request header and body part to the server, and gets the data returned by the server, the function returns the body part, and the returned network code state can be obtained using Getresponsecode.
This concludes.
Combined HttpURLConnection I made a little demo
Use asynchronous Asynctask to download server-side files and display progress using ProgressBar.
Server-side code (NODEJS):(the login and password are not validated here)
var http = require (' http ');
var querystring = require (' querystring ');
var url = require (' URL ');
var fs = require ("FS");
function Create (req,res) {var pathname = Url.parse (req.url). Pathname;
if (pathname = = "/upload") {//Read file Console.log ("Current path" +__dirname);
Fs.open (__dirname+ '/test.txt ', "R", (ERR,FD) => {if (err) {if (Err.code = = "Enoent") {
Console.error (' myfile does not exist ');
}else{throw err;
} res.write ("Read file failed");
Res.end (); }else{console.log ("file opened successfully.)
");
Console.log ("Prepare to read file:");
var buf = new Buffer (102400); Fs.read (FD, buf, 0, buf.length, 0, (err, bytes) => {if (err) {Console.log (
ERR);
Res.write ("Read file failed");
Res.end ();
} Console.log (bytes + "bytes read");
Output Read Only bytes if (bytes > 0) {console.log (buf.slice (0, bytes). toString ());
Res.writehead {' content-length ': bytes,
' Content-type ': ' Text/plain '});
Res.write (Buf.tostring ());
Res.end ();
});
}
});
}else {var postdata = ';
Req.on ("Data", function (chunk) {postdata + = chunk;
});
Req.on (' End ', function () {postdata = Querystring.parse (postdata);
Console.log (PostData);
Res.writehead (' {content-type:text/html;charset=utf-8} ');
if (!postdata) {res.write ("request parameter is null");
else {console.log ("end");
Res.write ("200");
} res.end (); ()}} http.createserver (Create). Listen (1234);
Android Section
Login loginactivity
Package com.asynctask;
Import android.content.Intent;
Import Android.os.Handler;
Import Android.os.Message;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;
Import Org.json.JSONObject;
Import Java.io.BufferedInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
public class Loginactivity extends Appcompatactivity implements View.onclicklistener {Button login;
EditText UserName;
EditText userpwd;
Private Intent Intent; Private Handler handler= New Handler () {@Override public void Handlemessage (msg) {s
Uper.handlemessage (msg);
if (Msg.what = =) {Toast.maketext (Getapplicationcontext (), "Login Successful", Toast.length_long). Show (); StartActivity (intent);
}else{Toast.maketext (Getapplicationcontext (), "User name or password error", Toast.length_long). Show ();
}
}
};
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_login);
Login = (Button) Findviewbyid (R.id.login);
UserName = (edittext) Findviewbyid (r.id.username);
Userpwd = (edittext) Findviewbyid (R.ID.PWD);
Login.setonclicklistener (this);
Intent = new Intent ();
Intent.setclass (This,mainactivity.class);
@Override public void OnClick (View v) {switch (V.getid ()) {case R.id.login: if (!userpwd.gettext (). Equals ("") && Username.gettext (). Equals ("")) {Toast.maketext (this, "user
Name or password is blank ", Toast.length_long). Show ();
}else{confirm ();
} break; }} private void confirm () {New Thread (new Runnable () {@Override public void run () {
HttpURLConnection conn = null; try{url url = new URL ("http://10.0.2.2:1234");//emulator access local address cannot use 127.0.0.1 conn = ( httpurlconnection) url.openconnection (); Here just created this object, and did not perform the real request operation//set whether to httpurlconnection output because this is the POST request parameter to be placed in the HTTP//body
Therefore, you need to set to True by default false Conn.setdooutput (TRUE);
Whether the data can be read from the httpurlconnection default is True Conn.setdoinput (true);
The POST request cannot use the cache Conn.setusecaches (false);
Conn.setrequestmethod ("POST");
Conn.setconnecttimeout (5000);//connection time is 5 seconds if the connection is not successful in 5 seconds, disconnect the connection conn.setreadtimeout (5000);
Conn.setrequestproperty ("Content-type", "Application/json"); Conn.connect ();//Start connection//getoutputstream will be implicitly connect all that is not execute Conn.connect function can also outputstream o
Utputstream = Conn.getoutputstream ();
Jsonobject json = new Jsonobject ();
Json.put ("Name", Username.gettext (). toString ());
Json.put ("pwd", Userpwd.gettext (). toString ());
Outputstream.write (Json.tostring (). GetBytes ()); int response = Conn.getresponsecode (); Connection Status Code if (response = = HTTPURLCONNECTION.HTTP_OK) {//Processing server response results//start fetching Data Geti The Nputstream () method only formally sends data to the server Bufferedinputstream bis = new Bufferedinputstream (Conn.getinputstream ()
);
Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
int Len;
byte[] arr = new byte[1024]; while (len = Bis.read (arr))!=-1) {Bos.write (Arr,0,len);
Bos.flush ();
} bos.close ();
LOG.E ("BOS Data:", bos.tostring ());//: System.out.println (Integer.parseint (bos.tostring ())); if (Integer.parseint (bos.tostring ()) = {msg = new message ()
;
Msg.what = 200;
Handler.sendmessage (msg);
}}catch (Exception e) {log.i ("exception", E.getmessage ());
}}). Start ();
}
}
Download file mainactivity
Package com.asynctask;
Import Android.os.AsyncTask;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.ProgressBar;
Import Android.widget.Toast;
Import Java.io.BufferedInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URI;
Import Java.net.URL;
public class Mainactivity extends appcompatactivity implements view.onclicklistener{private ProgressBar ProgressBar;
Private Button Download;
Private EditText Edittext_url;
Private String URL = "Http://10.0.2.2:1234/upload";
private int length;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);
ProgressBar = (ProgressBar) Findviewbyid (R.id.progressbar);
Progressbar.setmax (100);
Download = (Button) Findviewbyid (R.ID.DOWNLOAD_BTN);
Edittext_url = (edittext) Findviewbyid (R.id.upload_url);
Edittext_url.settext (URL);
Download.setonclicklistener (this);
@Override public void OnClick (View v) {switch (V.getid ()) {case R.ID.DOWNLOAD_BTN:
UploadFile up = new UploadFile ();
Up.execute (URL);
Break }//Asynchronous download File class UploadFile extends asynctask<string,integer,string>{@Override prot ected void OnPreExecute () {progressbar.setprogress (0);//Set progress bar to 0 Toast.maketext (Mainactivity.this,
"Start Download", Toast.length_short). Show ();
Super.onpreexecute (); } @Override protected String Doinbackground (String ... params) {//Establish a connection to the server and start downloading InputStream is = DownloadFile (Params[0]);
Bufferedinputstream bis = new Bufferedinputstream (IS);
String filename = "MyFile.txt";
try{fileoutputstream fos= openfileoutput (filename, mode_private);
Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
int Len;
byte[] arr = new byte[1024];
int count = 0;
while (len = Bis.read (arr))!=-1) {bos.write (Arr,0,len);
Count +=len;
Publishprogress (count);
Bos.flush ();
} bos.close ();
Fos.write (Bos.tobytearray ());
Fos.flush ();
Fos.close ();
LOG.E ("Save Success", "success");
}catch (Exception e) {e.printstacktrace ();
return null;
//Update UI @Override protected void Onprogressupdate (Integer ... values) {log.isloggable ("onprogressupdate", Values[0]);
System.out.println (Values[0]);
Progressbar.setprogress ((values[0] *)/length);
if (values[0] = length) {Toast.maketext (mainactivity.this, "Download Successful", Toast.length_short). Show ();
} super.onprogressupdate (values); The last function executed by//asynchronously @Override protected void OnPostExecute (String s) {Super.onpostexecute (s)
);
}/* str: The server address is connected to the server and gets the file stream returned by the server * * Private inputstream DownloadFile (String str) {
HttpURLConnection conn = null;
try {URL url = new URL (str);
conn = (httpurlconnection) url.openconnection ();
Construction Request Body (POST) Conn.setrequestmethod ("post");
Conn.setdoinput (TRUE);
Conn.setdooutput (TRUE);
Conn.setusecaches (FALSE); Conn.Setreadtimeout (3000);
Conn.setconnecttimeout (3000);
OutputStream OS = Conn.getoutputstream ();//implicitly connected to System.out.println (OS); InputStream is = Conn.getinputstream (); Establish a connection to the server and obtain the entity portion returned by the server if (Conn.getresponsecode ()!=) {Toast.maketext (mainactivity.th
IS, "Connection failed", Toast.length_short. Show ();
Length = Conn.getcontentlength ();
System.out.println (length);
Establish a connection successful return is;
Save (IS);
catch (Malformedurlexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
return null; * * * Save file * is: File stream * */private void Save (InputStream is) {Bufferedinputstream bis = new B
Ufferedinputstream (IS);
String filename = "MyFile.txt";
try{fileoutputstream fos= openfileoutput (filename, mode_private); Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
int Len;
byte[] arr = new byte[1024];
while (len = Bis.read (arr))!=-1) {bos.write (Arr,0,len);
Bos.flush ();
} bos.close ();
Fos.write (Bos.tobytearray ());
Fos.flush ();
Fos.close ();
LOG.E ("Save Success", "success");
}catch (Exception e) {e.printstacktrace ();
}
}
}
Interface Display
Activity_login.xml
<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:id=" @+id/activity_login "android:layout_width= "Match_parent" android:layout_height= "match_parent" tools:context= "com.asynctask.LoginActivity" > <edit Text android:id= "@+id/username" android:hint= "username" android:layout_margintop= "150DP" Androi D:layout_centerhorizontal= "true" android:layout_width= "150DP" android:layout_height= "50DP"/> <e Dittext android:id= "@+id/pwd" android:layout_below= "@id/username" android:hint= "password" Androi D:layout_centerhorizontal= "true" android:layout_width= "150DP" android:layout_height= "50DP"/> <b Utton android:id= "@+id/login" android:text= "Login" android:textsize= "15DP" Android:layout_bel ow= "@id/pwd" Android:layOut_width= "Match_parent" android:layout_height= "50DP"/> </RelativeLayout>
Download Interface Activity_main.xml
<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:id=" @+id/activity_main "Android:layout_width=" mat
Ch_parent "android:layout_height=" match_parent "tools:context=" com.asynctask.MainActivity "> <edittext Android:id= "@+id/upload_url" android:hint= "Please enter the download address" android:layout_width= "300DP" android:layout _height= "50DP"/> <button android:id= "@+id/download_btn" android:text= "Download" android:layou t_torightof= "@id/upload_url" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"/>
; <progressbar android:id= "@+id/progressbar" style= "Android:attr/progressbarstylehorizontal" and
roid:layout_below= "@id/upload_url" android:layout_width= "match_parent" android:layout_height= "20DP"/> </RelativeLayout> ≪/