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[]
。
-
execute(Params... params)
,执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。 -
onPreExecute()
, 在execute(Params... params)
被调用后立即执行,一般用来在执行后台任务前对 UI 做一些标记。 -
doInBackground(Params... params)
, 在onPreExecute()
完成后立即执行,用于执行较为费时的操作,此方法将接受输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)
来更新进度信息。 -
onProgressUpdate(Progress... values)
, 在调用publishProgress(Progress... values)
时,此方法被执行,直接将进度信息更新到 UI 组件上。 -
onPostExecute(Result result)
, 当后台操作结束时,此方法会被调用,计算结果将作为参数传递到此方法中,直接将结果显示到 UI 组件上。
注意:
- 异步任务的实例必须在 UI 线程中调用。
execute(Params... params)
方法必须在 UI 线程中调用。- 不要手动调用
onPreExecute()
,doInBackground(Params... params)
,onProgressUpdate(Progress... values)
,onPostExecute(Result result)
这几个方法。- 不能在
doInBackground(Params... params)
中更改 UI 组件的信息。- 一个任务实例只能执行一次,如果执行第二次将会抛出异常。
URL Object
- create a URL Object named
url
from the String of URL. we set RequestMethod as "GET" - Using the url object to make http request. method
makeHttpRequest()
makeHttpRequest
:
- call method
url.openConnection()
to get a URLConnection object, or one of its protocol specific subclasses, java.net.HttpURLConnection this case.- We can use this URLConnection object to setup parameters and general request properties before connecting.
- Call
urlConnection.connect()
.- Get inputStream by the method
urlConnection.getInputStream()
.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?
- We want to retrieve data from the server.
- 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.
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