Android的网络编程大家基本都熟悉,Http的Get,Post请求与其他语言的开发大同小异,可以采用Android自带的网络开发包,也可以采用Apache的开源网络编程包。本文介绍一个支持SPDY的开发包OkHttp,关于SPDY的知识,大家可以从维基百科和百度百科上面找到,基本就是增强版的Http。
OkHttp is an HTTP client that’s efficient by default:
- SPDY support allows all requests to the same host to share a socket.
- Connection pooling reduces request latency (if SPDY isn’t available).
- Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
示例代码
GET A URL
This program downloads a URL and print its contents as a string. Full source.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | OkHttpClient client = new OkHttpClient(); String get(URL url) throws IOException { HttpURLConnection connection = client.open(url); InputStream in = null; try { // Read the response. in = connection.getInputStream(); byte[] response = readFully(in); return new String(response, "UTF-8"); } finally { if (in != null) in.close(); } } |
OkHttpClient client = new OkHttpClient(); String get(URL url) throws IOException { HttpURLConnection connection = client.open(url); InputStream in = null; try { // Read the response. in = connection.getInputStream(); byte[] response = readFully(in); return new String(response, "UTF-8"); } finally { if (in != null) in.close(); } }
POST TO A SERVER
This program posts data to a service. Full source.
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 | OkHttpClient client = new OkHttpClient(); String post(URL url, byte[] body) throws IOException { HttpURLConnection connection = client.open(url); OutputStream out = null; InputStream in = null; try { // Write the request. connection.setRequestMethod("POST"); out = connection.getOutputStream(); out.write(body); out.close(); // Read the response. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected HTTP response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } in = connection.getInputStream(); return readFirstLine(in); } finally { // Clean up. if (out != null) out.close(); if (in != null) in.close(); } } |
OkHttpClient client = new OkHttpClient(); String post(URL url, byte[] body) throws IOException { HttpURLConnection connection = client.open(url); OutputStream out = null; InputStream in = null; try { // Write the request. connection.setRequestMethod("POST"); out = connection.getOutputStream(); out.write(body); out.close(); // Read the response. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected HTTP response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } in = connection.getInputStream(); return readFirstLine(in); } finally { // Clean up. if (out != null) out.close(); if (in != null) in.close(); } }
MAVEN 依赖库配置
<dependency> <groupId>com.squareup.okhttp</groupId> <artifactId>okhttp</artifactId> <version>1.2.0</version> </dependency>