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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容

  • 1、初页 初页作为手机端制作动态海报的app,面向C端,门槛极低,上手简单容易,可在App store免费下载,直...
    摆渡人memory阅读 4,833评论 0 22
  • 一直以来我都觉察到如果是上班或是出去见朋友我会比较开心,但是回家我就会有些难过,对此我有些莫名其妙,这到底是为什么...
    百合儿阅读 97评论 2 0