Three ways Android requests the network
When requesting the network, the commonly used submission method is a post or get request. The post request is safe and the transmission size is unlimited, but the amount of code is more. The get request is that the browser has a size limit. The information submitted by the user is in the browser's address bar It is not safe to show
In Android, the request for network connection needs to be added. After 4.0, a thread needs to be started. When the network is requested, it is transmitted in a stream.
The first step is to use the system URL to connect to the Internet
(Proficiently understand that this is needed when the server needs to pass in a special request header)
get
About names and passwords are the data that users input to submit
// 1. Set the connected network address, the get request is to stitch the content submitted by the user to the URL. Important note: in the Android test, the ip address cannot be written to localhost
Because the Android phone cannot recognize the local loopback address, it must be the specified IP address, otherwise it will not be executed when the response code is obtained in one line, no error will be reported, and the server will not get the submitted information.
It will not make any feedback, so there is no execution when the feedback is obtained
String path = "http://172.17.25.55:8080/login/LoginServlet?username="+ names +" & password = "+ passwords;
// 2. Create a URL connection instance
URL url = new URL (path);
// 3. Open a connection through the URL connection instance and force it into HttpURLConnection
HttpURLConnection httpurlconn = (HttpURLConnection) url.openConnection ();
// Then set the request method, here must be capitalized, GET
httpurlconn.setRequestMethod ("GET");
// Use the forced connection to set the request response timeout
httpurlconn.setConnectTimeout (5000);
// Get the response code returned by the server
int responseCode = httpurlconn.getResponseCode ();
// If the response code is 200, it is success, 206 is partial success, 404 cannot find the page, 504, etc. is an internal server error
if (responseCode == 200) {
// After successful response, get the data returned by the server, the server returns as a byte stream
InputStream ins = httpurlconn.getInputStream ();
// Read content shows that because networking requires thread opening and the UI does not allow child threads to update, write a method on the UI thread to update on the UI thread
}
post
About names and passwords are the data that users input to submit
// 1. Request path ☆☆☆☆☆☆☆ Important note: in the Android test, the IP address cannot be written to localhost
Because the Android phone cannot be used as the server, the local loopback address cannot be used, and must be the specified IP address, otherwise it will not be executed when the response code is obtained, and no error will be reported.
The server ca n’t get the submitted information and will not make any feedback, so there is no execution when the feedback is obtained
String path = "http://172.17.25.55:8080/login/";
// 2. Create a URL connection instance
URL url = new URL (path);
// 3. Open a connection through the URL connection instance and force it into HttpURLConnection
HttpURLConnection con = (HttpURLConnection) url.openConnection ();
// Use the forced connection to set the request response timeout
con.setConnectTimeout (5000);
// Then set the request method, here must capitalize GET ☆☆☆☆
con.setRequestMethod ("POST");
// request content ☆☆☆☆☆☆☆
String data = "username =" + names + "& password =" + passwords;
// The request method is fixed and must be written in this way, including upper and lower case. This is ☆☆☆☆☆☆☆
con.setRequestProperty ("Content-Type", "application / x-www-form-urlencoded");
// The length of the request body (content) is fixed and must be written in this way, including upper and lower case. This is ☆☆☆☆☆
con.setRequestProperty ("Content-Length", data.length () + "");
con.setDoOutput (true); // Set a mark to allow output data ☆☆☆☆☆
// Write the data and submit the data that our group spelled to the server to submit in the form of streaming ☆☆☆☆
con.getOutputStream (). write (data.getBytes ())
int responseCode = con.getResponseCode ();
// If the response code is 200, it is success, 206 is partial success, 404 cannot find the page, 504, etc. is an internal server error
if (responseCode == 200) {
// After successful response, get the data returned by the server, the server returns as a byte stream
InputStream ins = httpurlconn.getInputStream ();
// Read content shows that because networking requires thread opening and the UI does not allow child threads to update, write a method on the UI thread to update on the UI thread
}
The second step is to use the system structure to learn from Alpha's encapsulated classes (understand). The reason is that the request header information is encapsulated but it is too complicated, and third parties can replace it
//[2.1]Define the details of the path to be submitted in the get method
Get
// 1. Set the connected network address, use URLEncoder to encode the data submitted by the user so that Chinese can be submitted, and the user's information has some guarantees
About names and passwords are data submitted by users
String path = "http://172.17.25.55:8080/login/LoginServlet?username=" + URLEncoder.encode (names, "utf-8") + "& password =" + URLEncoder.encode (passwords, "utf-8 ");
// 2. Get the strength of httpclient and directly subclass it
DefaultHttpClient dehttp = new DefaultHttpClient ();
// 3. Prepare get request
HttpGet get = new HttpGet (path);
// 4. Performing a request returns the server response result
HttpResponse httpresponse = dehttp.execute (get);
// 5. Get the server response code
int statusCode = httpresponse.getStatusLine (). getStatusCode ();
if (statusCode == 200) {
// 6. Get the data returned by the server and return it as an entity
InputStream content = httpresponse.getEntity (). GetContent ();
// 7. Read the display result
}
Post
String path = "http://172.17.25.55:8080/login/LoginServlet";
// 2. Get the strength of httpclient and directly new his subclass
DefaultHttpClient dehttp = new DefaultHttpClient ();
// 3 prepare post request
HttpPost post = new HttpPost (path);
// 4. Start to prepare the text of the post submission, with the formation of key-value pairs
/4.1 Prepare a collection to store NameValuePair
List <NameValuePair> an = new ArrayList <NameValuePair> ();
//4.2 Create NameValuePair subclass implementation is BasicNameValuePair
// Create the data that needs to be submitted in the form of key value. The key is the key that the server fetches according to,
BasicNameValuePair bnp1 = new BasicNameValuePair ("username", names);
BasicNameValuePair bnp2 = new BasicNameValuePair ("password", passwords);
//4.3 Add to collection
an.add (bnp1);
an.add (bnp2);
//4.4 Prepare entity entity new a subclass to implement UrlEncodedFormEntity
// UrlEncodedFormEntity needs a List <? Extends NameValuePair>
UrlEncodedFormEntity uf = new UrlEncodedFormEntity (an);
//4.5 set entity
post.setEntity (uf);
// 5. Performing a request returns the server response result
HttpResponse httpresponse = dehttp.execute (post);
// 6. Get the server response code
int statusCode = httpresponse.getStatusLine (). getStatusCode ();
if (statusCode == 200) {
// 7. Get the data returned by the server and return it as an entity
InputStream content = httpresponse.getEntity (). GetContent ();
// 8. Read the display result
}
The third step is to use the open source project Asynhttpclient (proficient)
Note: To use Asynhttpclient, you need to import a third-party com package. After the guide is completed, an error will be reported. If a city registration error is deleted, there is no guide package. The imported package is available
About names and passwords are data submitted by users
Get
// 1. Set the connected network address, use URLEncoder to encode the data submitted by the user so that Chinese can be submitted, and the user's information has some guarantees
String path = "http://172.17.25.55:8080/login/LoginServlet?username="
+ URLEncoder.encode (names, "utf-8") + "& password =" + URLEncoder.encode (passwords, "utf-8");
// 2. Create an asynchttp
AsyncHttpClient ashttp = new AsyncHttpClient ();
// 3. Make a get request and pass in a path, and an AsyncHttpResponseHandler response thread
ashttp.get (path, new AsyncHttpResponseHandler () {
// Callback method for successful request
@Override
public void onSuccess (int statusCode, Header [] headers, byte [] responseBody) {
// The text returned by the responseBody server statusCode The status code returned by the server, the response header information returned by the header server
try {
Toast.makeText (MainActivity.this, new String (responseBody, "gbk"), 0) .show ();
} catch (UnsupportedEncodingException e) {
e.printStackTrace ();
}
}
// Method for request failure callback
@Override
public void onFailure (int statusCode, Header [] headers,
byte [] responseBody, Throwable error) {
Toast.makeText (MainActivity.this, new String (responseBody), 0) .show ();
}
});
Post
String path = "http://172.17.25.55:8080/login/LoginServlet";
// Create an asynchttp
AsyncHttpClient ashttp = new AsyncHttpClient ();
// Preparing the request body content
RequestParams params = new RequestParams ();
params.put ("username", names);
params.put ("password", passwords);
// Request a post request
ashttp.post (path, params, new AsyncHttpResponseHandler () {
@Override
public void onSuccess (int statusCode, Header [] headers, byte [] responseBody) {
try {
Toast.makeText (MainActivity.this, new String (responseBody, "gbk"), 0) .show ();
} catch (UnsupportedEncodingException e) {
e.printStackTrace ();
}
@Override
public void onFailure (int statusCode, Header [] headers, byte [] responseBody, Throwable error) {
Toast.makeText (MainActivity.this, new String (responseBody), 0) .show ();
}
});