Analysis on Net Request for Android Dev

Desc of Net Request

It’s necessary to analysis on net reqeust for android dev. Almost all android app depend on network on data interchange.

Net Request

Net Request has three levels, simple Json reqeust, native http request and native socket request.

Simple Json or Form Request

Here, let’s retrofit async request as example.

Retrofit turns your HTTP API into a Java interface.

1
2
3
4
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}

The Retrofit class generates an implementation of the GitHubService interface.

1
2
3
4
5
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();

GitHubService service = retrofit.create(GitHubService.class);

Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.

1
Call<List<Repo>> repos = service.listRepos("octocat");

Use annotations to describe the HTTP request:

  • URL parameter replacement and query parameter support

  • Object conversion to request body (e.g., JSON, protocol buffers)

  • Multipart request body and file upload

Form request as follows:

FORM ENCODED AND MULTIPART

Methods can also be declared to send form-encoded and multipart data.

Form-encoded data is sent when

is present on the method. Each key-value pair is annotated with ```@Field``` containing the name and the object providing the value.
1
2
3
4
5

```java
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

Multipart requests are used when

is present on the method. Parts are declared using the ```@Part``` annotation.
1
2
3
4
5

```java
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

Native Http Request

Native http request allows you composing http packet and upload to server. Here let’s uploading a image as a example. codes as foloows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
FileInputStream fis = null;
DataOutputStream dos = null;
InputStream responseIs = null;
try {
operateImage = images[0];
Uri uri = Uri.parse(operateImage.getResUri());
String path = uri.getHost() + uri.getPath();
File file = new File(path);
fis = new FileInputStream(file);

String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";

URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
/**
* setting http packet header
*/
// setting the packet size, in case of phone crashing for out memory
//httpURLConnection.setChunkedStreamingMode(1280 * 1024);// 1280K
// allow input and output
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);

/**
* setting fields
*/
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
httpURLConnection.setConnectTimeout(10 * 1000);

// construct the data
StringBuilder textEntity = new StringBuilder();
if (params == null) {
params = new HashMap<>(0);
}
Iterator<String> iterator = params.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = params.get(key);
textEntity.append(twoHyphens + boundary + end);
textEntity.append("Content-Disposition:form-data;name=" + key + end + end);
textEntity.append(value.toString());
textEntity.append(end);
}
textEntity.append(twoHyphens + boundary + end);
textEntity.append("Content-Disposition:form-data;" + "name=\"" + paramsFilename + "\";filename=\"" + file.getName()
+ "\"" + end);
textEntity.append(end);

/**
* getting http connection
*/
dos = new DataOutputStream(httpURLConnection.getOutputStream());
byte[] text = textEntity.toString().getBytes();

/**
* setting http body
*/
dos.write(text);

int totalSize = fis.available();
int progressSize = 0;

int bufferSize = 1024 * 10;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fis.read(buffer)) != -1) {
dos.write(buffer, 0, length);
progressSize += length;
publishProgress(progressSize, totalSize);

}
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
fis.close();
dos.flush();

responseIs = httpURLConnection.getInputStream();
String response = readStreamToByteArray(responseIs);
return response;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
fis = null;
}
}

if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
dos = null;
}
}

if (responseIs != null) {
try {
responseIs.close();
} catch (IOException e) {
e.printStackTrace();
responseIs = null;
}
}
}

Native TCP/IP Request

Here let’s socket program as example to show the native tcp/ip request.

UDP

udp sever codes as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServer {
public static void main(String[] args) {
// declare UPD socket,DatagramSocket
DatagramSocket socket = null;
try {
// port
socket = new DatagramSocket(1234);
// buffer
byte data[] = new byte[512];
// write data
DatagramPacket packet = new DatagramPacket(data, data.length);
// block to receive msg from client
socket.receive(packet);

String msg = new String(packet.getData(), packet.getOffset(),
packet.getLength());
System.out.println(msg);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
socket.close();
}
}
}

udp client codes as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UdpClient {
public static void main(String[] args) {
DatagramSocket socket = null;
String msg = null;
try {
socket = new DatagramSocket();
// read from standard input
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
while (!(msg = reader.readLine()).equalsIgnoreCase("exit")) {
// contruct to server
InetAddress serverAddress = InetAddress.getByName("127.0.0.1");
//
DatagramPacket packet = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, serverAddress, 1234);
// send msg
socket.send(packet);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
socket.close();
}
}
}

TCP

tcp server codes as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
// declare a server socket
ServerSocket serverSocket = null;
// declare a socket watting for client conn
Socket socket = null;
try {
int temp;
// port
serverSocket = new ServerSocket(5937);
// block to conn
socket = serverSocket.accept();
// get input from client
InputStream inputStream = socket.getInputStream();
// reading and print
byte[] buffer = new byte[512];
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

tcp client as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package me.bym.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
public static void main(String[] args) {
// declare a socket
Socket socket = null;
try {
String msg = null;
// connect to server
socket = new Socket("127.0.0.1", 5937);
// get input from keyboard (standard input)
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
OutputStream outputStream = socket.getOutputStream();
while (!(msg = reader.readLine()).equalsIgnoreCase("exit")) {
outputStream.write(msg.getBytes());
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

By the way, you can use other framework to contruct tcp/ip server and client, likeNetty.