android studio環(huán)境配置
在Module的build.gradle文件中增加依賴包:
dependencies {
···
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
基本使用
主要有發(fā)Get和Post請(qǐng)求兩種
Get請(qǐng)求
新建工程恋腕。先看代碼
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
Response response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(
new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://raw.github.com/square/okhttp/master/README.md").build();
response = client.newCall(request).execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
).start();
try {
Log.v("mylog", response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
結(jié)果如下:
其中由于UI線程不能發(fā)網(wǎng)絡(luò)請(qǐng)求,必須開(kāi)新的線程來(lái)進(jìn)行網(wǎng)絡(luò)處理扮休。
其中主要代碼是:
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://raw.github.com/square/okhttp/master/README.md").build();
Response response = client.newCall(request).execute();
Log.v("mylog", response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
Response類:
(1)isSuccessful() 方法
public boolean isSuccessful() //如果返回碼是[200..300),該函數(shù)則返回true。
(2)body() 方法
Response response;
ResponseBody responseBody = response.body() //返回ResponseBody類
String string = responseBody.string()
ResponseBody類的string方法谬哀,將response作為string返回逞怨。
Post請(qǐng)求
新建工程捌省。先看代碼
public class MainActivity extends AppCompatActivity {
Response response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(
new Runnable() {
@Override
public void run() {
try {
testPost();
try {
if(response.isSuccessful()){
Log.v("mylog", response.body().string());
Log.v("mylog", response.header("Set-Cookie"));
}else {
Log.v("mylog", "Unexpected code " + response);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
).start();
}
public String GetJson(String PhoneNum, String VerifyCode) {
JSONObject jsn_login = new JSONObject();
try{
jsn_login.put("phoneNo",PhoneNum);
jsn_login.put("requestOtp",VerifyCode);
}catch (Exception e){}
return jsn_login.toString();
}
public void testPost() throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
RequestBody body = RequestBody.create(JSON, GetJson("11111111111","1234"));
Request request = new Request.Builder()
.url("http://localhost:8080/login.do")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.post(body)
.build();
response = client.newCall(request).execute();
}
}
(1)設(shè)置請(qǐng)求頭的方法:
1)對(duì)于header(String name, String value)
方法,使用name和value設(shè)置一個(gè)頭信息互订,如果請(qǐng)求中已經(jīng)存在響應(yīng)的信息那么直接替換掉吱肌。
2)而addHeader(String name, String value)
,如果請(qǐng)求頭中已經(jīng)存在name的name-value仰禽,那么還會(huì)繼續(xù)添加氮墨,請(qǐng)求頭中便會(huì)存在多個(gè)name相同而value不同的“鍵值對(duì)”。
(2)獲取返回頭的方法:
1)response.header("name")方法:如果header中有重復(fù)的吐葵,則返回最后出現(xiàn)的value规揪。如果沒(méi)有值,那么header(name)將返回null折联。
response.header("Set-Cookie")``` 代表獲取cookie粒褒。
2)response.headers()方法,獲取所有的header:返回一個(gè)list诚镰。為了獲取所有的Header奕坟,Headers類支持按index訪問(wèn)。
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
(3)Post請(qǐng)求提交Json數(shù)據(jù)
1)首先新建一個(gè)MediaType
MediaType代表的就是請(qǐng)求包體內(nèi)容的類型清笨。
例如月杉,MediaType.parse("application/json; charset=utf-8");這個(gè)就帶表請(qǐng)求體的類型為JSON格式的。
2)再通過(guò) RequestBody.create(MediaType, JSONDATA);
的方法來(lái)創(chuàng)建一個(gè) RequestBody
3)最后通過(guò)Request.Builder().Post(RequestBody)
方法來(lái)加入post數(shù)據(jù)抠艾。
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
f (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
(4)Post請(qǐng)求提交鍵值對(duì)
具體方法如下:
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
(5)Post方式提交文件
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File("README.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
(6)Post方式提交分塊請(qǐng)求
MultipartBuilder可以構(gòu)建復(fù)雜的請(qǐng)求體苛萎,與HTML文件上傳形式兼容。多塊請(qǐng)求體中每塊請(qǐng)求都是一個(gè)請(qǐng)求體检号,可以定義自己的請(qǐng)求頭腌歉。這些請(qǐng)求頭可以用來(lái)描述這塊請(qǐng)求,例如他的Content-Disposition齐苛。如果Content-Length和Content-Type可用的話翘盖,他們會(huì)被自動(dòng)添加到請(qǐng)求頭中。
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
異步Get請(qǐng)求
先看代碼
public class MainActivity extends AppCompatActivity {
Response response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testAsyncGet();
}
public void testAsyncGet() {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
System.out.println(request);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.v("mylog", "call = [" + call + "], response = [" + response + "]");
if (!response.isSuccessful()) {
throw new IOException("" + response);
}
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.v("mylog", headers.name(i) + ": " + headers.value(i));
}
System.out.println(response.body().string());
}
});
}
}
輸出如下:
https://github.com/square/okhttp/wiki/Recipes
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html
http://blog.csdn.net/biezhihua/article/details/50603624