Easy Tutorial
❮ Rsa Basic Idea Sql Different On And Where ❯

7.1.3 Android HTTP Request Method: HttpURLConnection

Category Android Basic Tutorial

Introduction to This Section:

>

In the previous two sections, we studied some conceptual aspects, the HTTP protocol and some protocol headers, and in this section, we are going to start coding. What we will learn in this section is one of the HTTP request methods provided by Android: HttpURLConnection. In addition to this, there is another method called HttpClient, which we will discuss in the next section! However, the former can be very cumbersome to use when the request becomes complex, while the latter is often used in Java packet capturing, which is Apache's, after all, not Google's own son. In version 4.4, HttpURLConnection has been replaced by OkHttp! Well, keeping up with the times, I decided to talk about HttpClient and then meet this OkHttp after that! By the way, in actual development, we generally do not use HttpURLConnection and HttpClient, but use third-party network request frameworks that others have encapsulated, such as: Volley, android-async-http, loopj, etc., because network operations involve asynchronous and multi-threading, which is very troublesome to do by oneself, so in actual development, we still use third-party directly! Of course, it's also good to learn, after all, the third party is also based on these, with high architectural style and various optimizations! Well, without further ado, let's start this section!


1. Introduction to HttpURLConnection

>

Answer: A versatile, lightweight HTTP client that can be used for HTTP operations suitable for most applications. Although the API provided by HttpURLConnection is relatively simple, this also makes it easier for us to use and extend. It inherits from URLConnection, an abstract class, and cannot be instantiated directly. By calling the openConnection() method to obtain an object instance, the default is with gzip compression;


2. Steps for Using HttpURLConnection

The steps for using HttpURLConnection are as follows:

>

PS: In addition to the above, sometimes we may also need to judge the response code, such as 200: if(conn.getResponseCode() != 200) then some processing Also, sometimes we may not need to pass any parameters, but directly access a page, we can directly use: final InputStream in = new URL("url").openStream(); Then read the stream directly, but this method is suitable for directly accessing the page, the actual implementation at the bottom is actually return openConnection().getInputStream(), and we can't set some request header things, so whether to write like this, you have to weigh it yourself!


3. Example of Using HttpURLConnection

>

Here we mainly write two different usage examples for GET and POST requests. We can get a stream from conn.getInputStream(), so we need to write a class to convert the stream into a binary array! The utility class is as follows:

StreamTool.java:

/**
 * Created by Jay on 2015/9/7 0007.
 */
public class StreamTool {
    //Read data from the stream
    public static byte[] read(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();
    }
}

Next, we can start our example!


1) Code Example of HttpURLConnection Sending GET Request

Running Effect Picture:

Core Part of the Code:

Layout: activity_main.xml

``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

&lt;TextView
    android:id="@+id/txtMenu"
    android:layout_width="

private final static String PIC_URL = "https://ww2.sinaimg.cn/large/7a8aed7bgw1evshgr5z3oj20hs0qo0vq.jpg"; private final static String HTML_URL = "https://www.baidu.com";

// For refreshing the interface private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0x001: hideAllWidget(); imgPic.setVisibility(View.VISIBLE); imgPic.setImageBitmap(bitmap); Toast.makeText(MainActivity.this, "Image loaded", Toast.LENGTH_SHORT).show(); break; case 0x002: hideAllWidget(); scroll.setVisibility(View.VISIBLE); txtshow.setText(detail); Toast.makeText(MainActivity.this, "HTML code loaded", Toast.LENGTH_SHORT).show(); break; case 0x003: hideAllWidget(); webView.setVisibility(View.VISIBLE); webView.loadDataWithBaseURL("", detail, "text/html", "UTF-8", ""); Toast.makeText(MainActivity.this, "Web page loaded", Toast.LENGTH_SHORT).show(); break; default: break; } } };

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setViews(); }

private void setViews() { txtMenu = (TextView) findViewById(R.id.txtMenu); txtshow = (TextView) findViewById(R.id.txtshow); imgPic = (ImageView) findViewById(R.id.imgPic); webView = (WebView) findViewById(R.id.webView); scroll = (ScrollView) findViewById(R.id.scroll); registerForContextMenu(txtMenu); }

// Define a method to hide all widgets: private void hideAllWidget() { imgPic.setVisibility(View.GONE); scroll.setVisibility(View.GONE); webView.setVisibility(View.GONE); }

@Override // Override the context menu creation method public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { MenuInflater inflator = new MenuInflater(this); inflator.inflate(R.menu.menus, menu); super.onCreateContextMenu(menu, v, menuInfo); }

// The method is triggered when the context menu is clicked @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.one: new Thread() { public void run() { try { byte[] data = GetData.getImage(PIC_URL); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { e.printStackTrace(); } handler.sendEmptyMessage(0x001); } }.start(); break; case R.id.two: new Thread() { public void run() { try { detail = GetData.getHtml(HTML_URL); } catch (Exception e) { e.printStackTrace(); } handler.sendEmptyMessage(0x002); } }.start(); break; case R.id.three: if (detail.equals("")) { Toast.makeText(MainActivity.this, "Request HTML first~", Toast.LENGTH_SHORT).show(); } else { handler.sendEmptyMessage(0x003); } break; } return true; }

Remember to add the Internet permission:

<uses-permission android:name="android.permission.INTERNET" />

Note:

>

The reason for using a handler doesn't need to be explained, right? Also, when we load HTML code, we use webView's loadDataWithBaseURL instead of loadData. If we use loadData, we will have to worry about the Chinese character garbled problem again, so... Using loadDataWithBaseURL, we don't have to worry about so much. Some pages may require us to submit some parameters, such as username and password: We just need to concatenate the corresponding parameters to the end of the URL, for example: http://192.168.191.1:8080/ComentServer/LoginServlet?passwd=123&name=Jack Then the server can get the corresponding parameters with getParamater("passwd"), and we can see these things clearly when we request, so GET is not secure! Also, one more thing to note is that Android has not allowed UI operations in non-UI threads since version 4.0!


2) HttpURLConnection sends POST request code example

>

There is naturally a POST request with GET. The HttpURLConnection we get through openConnection is the default for Get requests, So when we submit data using POST, we should set the relevant parameters in advance: conn.setRequestMethod("POST"); Also: conn.setDoOutput(true); conn.setDoInput(true); Set to allow input and output Also: conn.setUseCaches(false); The POST method cannot be cached and should be manually set to false, See the conn.setDoOutput(true); conn.setDoInput(true); // POST method cannot be cached, manually set to false conn.setUseCaches(false); // The data we are requesting: String data = "passwd=" + URLEncoder.encode(passwd, "UTF-8") + "&number=" + URLEncoder.encode(number, "UTF-8"); // Here you can write some request header stuff... // Get the output stream OutputStream out = conn.getOutputStream(); out.write(data.getBytes()); out.flush(); if (conn.getResponseCode() == 200) { // Get the response input stream object InputStream is = conn.getInputStream(); // Create a ByteArrayOutputStream object ByteArrayOutputStream message = new ByteArrayOutputStream(); // Define the read length int len = 0; // Define the buffer byte buffer[] = new byte[1024]; // Read in cycles according to the size of the buffer while ((len = is.read(buffer)) != -1) { // Write to the os object according to the length read message.write(buffer, 0, len); } // Release resources is.close(); message.close(); // Return string msg = new String(message.toByteArray()); return msg; } } catch (Exception e) { e.printStackTrace(); } return msg; }

// Because I don't have MyEclipse installed on my computer, and due to time constraints, I won't write a demo separately, I'll use the previous Eclipse demo! // In fact, it's enough to just look at the core code directly~ // Code download: HttpURLConnection Example.zip


4. Handling Cookie Issues

>

Before we discuss this, we must first understand two concepts: Session and Cookie. A Cookie is just a common form of the Session mechanism, and we can also use other methods as a unique identifier for the client side, which is determined by the server. The only thing that matters is that it can prove a client's identity! In addition to this method, we can also use URL rewriting methods to achieve this! So don't naively tell others: Session is just a Cookie!

Let's go through an example to help everyone understand this Cookie: After the piglet enters the account password and logs into the school's teaching system, and then successfully accesses the class schedule information, and then if you are using Chrome, press F12 to enter the development mode: Go to the Resources interface to see our Cookies:

Click on it and you can see the saved content, including the name; value; the domain where the cookie is located (domain); the directory where the cookie is located (path). Asp.net defaults to / which is the root directory; expiration time; Cookie size:

We can see that there is a Cookie field in the request header:

Well, now let's clear the Cookie (or wait a few minutes), and then visit the following link:

At this time, the page automatically jumps back to the login page! Of course, some other websites may pop up a dialog box saying "Login Timeout" and other similar things!

A brief summary of the simple process of an HTTP request login: Generally, when logging in: the server returns a Cookie through the Set-Cookie response header, and the browser saves this Cookie by default. When visiting related pages later, it will carry this Cookie and complete the visit through the Cookie request header. If there is no Cookie or the Cookie has expired, it will prompt the user with messages like not logged in, login timeout, access requires login, etc.!

And when we use HttpClient and HttpURLConnection, it is actually to simulate this process. After logging in, we get the cookie and send requests with it: The key code is as follows: Get the Cookie: conn.getHeaderField("Set-Cookie"); Request with Cookie: conn.setRequestProperty("Cookie", cookie);

In addition to this method of setting the request header, there is another compromise method: URL rewriting: It is to add a parameter like ...&sessionid=xxxxx on the original request link, and then let the server parse and judge! Get can be written like this, and the Post method is as follows:

Here we use the JSON string format, when receiving the request, the server takes out the content in the session and then makes a query!


5. Sending PUT requests with HttpURLConnection

>

The Put request may be unfamiliar to many friends, after all, we usually come into contact with more situations of GET and POST. At first, the piglet didn't know either, but later found out that it is almost the same as POST, and we only need to change a few things on the basis of POST to use it! And HttpClient also provides us with a HttpPut API, Let me post the request code I wrote in my own project below:

❮ Rsa Basic Idea Sql Different On And Where ❯