HTTP Network

HTTP Network

Overview

HTTP Request and Response

URL: uniform resource locator

Client and Server model

Internet Permission

Levels of permissions in Android

Normal Permissions

These permissions will be automatically granted by the system.

  • Access the Internet
  • Vibrate the device
  • Set the timezone
  • Network connectivity status

Dangerous Permissions

These permissions requested at runtime when app needs the permission pop up a dialog to ask for permission.

  • Use Camera
  • Access call log
  • Access Contacts
  • Record Audio

HTTP

  • HTTP means: HyperText Transfer Protocol
  • GET: means I'd like to get or retrieve some data from you.
  • POST: means I'd like to create some new information.
  • PUT: means I'd like to update some existing information.
  • DELETE: means that I'd like to delete some existing information on the server.

Android Framework

Abstraction: we access hardwares and other resource on our device by some kind of abstractions, that created by android.

Each layer focuses on solving a bit of the problem while the underlying layers focus on solving subsequently smaller problems until eventually.

Android System Architecture

App, Framework, Android Operating System, Physical Device Hardware

Soonami app

AsyncTask

AsyncTask Difination

public abstract class AsyncTask<Params, Progress, Result>{}
  • Params: 啟動任務執行的輸入參數
  • Progress: 后臺任務執行的進度
  • Result: 后臺計算結果的類型
  • *在特定場合下,并不是所有類型都被使用,如果沒有被使用,可以用 Java.lang.Void 類型代替。

異步任務的一般執行步驟

  • 可變長參數列表:
  • 在下面的代碼中,出現了如 execute(Params... params) 這樣的寫法,表示可變長參數列表。
  • 其語法就是參數類型后面跟 ...
  • 表示此處接受的參數為 0 到多個 Object 對象作為參數,或者是一個 Object[]
  1. execute(Params... params),執行一個異步任務,需要我們在代碼中調用此方法,觸發異步任務的執行。
  2. onPreExecute(), 在 execute(Params... params) 被調用后立即執行,一般用來在執行后臺任務前對 UI 做一些標記。
  3. doInBackground(Params... params), 在 onPreExecute() 完成后立即執行,用于執行較為費時的操作,此方法將接受輸入參數和返回計算結果。在執行過程中可以調用 publishProgress(Progress... values) 來更新進度信息。
  4. onProgressUpdate(Progress... values), 在調用 publishProgress(Progress... values) 時,此方法被執行,直接將進度信息更新到 UI 組件上。
  5. onPostExecute(Result result), 當后臺操作結束時,此方法會被調用,計算結果將作為參數傳遞到此方法中,直接將結果顯示到 UI 組件上。

注意:

  1. 異步任務的實例必須在 UI 線程中調用。
  2. execute(Params... params) 方法必須在 UI 線程中調用。
  3. 不要手動調用 onPreExecute(), doInBackground(Params... params), onProgressUpdate(Progress... values), onPostExecute(Result result) 這幾個方法。
  4. 不能在 doInBackground(Params... params) 中更改 UI 組件的信息。
  5. 一個任務實例只能執行一次,如果執行第二次將會拋出異常。

URL Object

  1. create a URL Object named url from the String of URL. we set RequestMethod as "GET"
  2. Using the url object to make http request. method makeHttpRequest()

makeHttpRequest:

  1. call method url.openConnection() to get a URLConnection object, or one of its protocol specific subclasses, java.net.HttpURLConnection this case.
  2. We can use this URLConnection object to setup parameters and general request properties before connecting.
  3. Call urlConnection.connect().
  4. Get inputStream by the method urlConnection.getInputStream().
  5. readFromStream:
/**
 * Convert the {@link InputStream} into a String which contains the
 * whole JSON response from the server.
 */
private String readFromStream(InputStream inputStream) throws IOException {
    StringBuilder output = new StringBuilder();
    if (inputStream != null) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line = reader.readLine();
        while (line != null) {
            output.append(line);
            line = reader.readLine();
        }
    }
    return output.toString();
}

HTTP request method type

HTTP is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client an server.

  • GET(read): Requests data from a specified resource.
  • POST(write): Submits data to be processed to a specified resource.
The GET Method

Query string(name/value pairs) is sent in the URL of a GET request:

/test/demo_form.php?name1=value1&name2=value2

Some other notes on GET requests:

  • GET requests can be cached
  • GET requests remain in the browser history
  • GET requests can be bookmarked
  • GET requests should never be used when dealing with sensitive data
  • GET requests have length restrictions
  • GET requests should be used only to retrieve data
The POST Method

The query string(name/value pairs) is sent in the HTTP message body of a POST request:

POST /test/demo_form.php HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2

Some other notes on POST requests:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length
In our code
Set request method

In the Soonami app HTTP request, we using the GET HTTP request method.

urlConnection.setRequestMethod("GET");

Why are we using a GET instead of a POST?

  1. We want to retrieve data from the server.
  2. We're not posting new information to the server.
create connect

The following line actually establishes the HTTP connection.

urlConnection.connect();
Receive the response

we can get the Status Code.

Common HTTP Status Codes

Status Code Description
200 OK - request received, everything normal
301 Moved permanently
404 Page not found
500 Internal server error

The response status code may in the JSON file we get.

we can get response code by the method HttpURLConnection.getResponseCode

Reading from an input stream

What we receive is an input stream, which means just bytes stream does not represent a file or a webpage or even media content. It's just a stream of information.

In our app, the input stream is just text, we can use InputStreamReader to handle it. InputStreamReader read one character at one time, so we need to Wrapping it in BufferdReader to read a line at a time.

InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferdReader reader = new BufferdReader(inputStreamReader);
String line = reader.readLine();
while(line != null){
    output.append(line); // output is an object of StringBuilder
    line = reader.readLine();
}

String and String Builder

  • String is immutable (Can't change once created)
  • StringBuilder is mutable (Can change once created)
Exception

throw

try-catch(-finally) block: finally block executed before return statement, can be used to release resources.

execute order:

start=>start: start
end=>end: end
try=>operation: try block
isThrow=>condition: throw Exception?
catch=>operation: catch block
isReturn=>condition: return?
statementInReturn=>operation: Statements in return
finally=>operation: finally block
return=>operation: return statement

start->try->isThrow
isThrow(yes)->catch
isThrow(no)->isReturn
catch->isReturn
isReturn(yes)->statementInReturn
isReturn(no)->finally
statementInReturn->finally
finally->return
return->end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1、初頁 初頁作為手機端制作動態海報的app,面向C端,門檻極低,上手簡單容易,可在App store免費下載,直...
    擺渡人memory閱讀 4,923評論 0 22
  • 一直以來我都覺察到如果是上班或是出去見朋友我會比較開心,但是回家我就會有些難過,對此我有些莫名其妙,這到底是為什么...
    百合兒閱讀 121評論 2 0