android get请求最长字符,Android OKHTTP3的GET和POST方法(带basic auth)
使用前需要在Gradle Script中的build gradle中引入:
compile 'com.squareup.okio:okio:1.13.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
GET
//創(chuàng)建OkHttpClient對象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
final Request request = new Request.Builder()
.url("http://172.20.192.168:8080/getbookByFrom?name=android基礎(chǔ)&price=50")//請求的url
.get()//設(shè)置請求方式,get()/post() 查看Builder()方法知,在構(gòu)建時默認(rèn)設(shè)置請求方式為GET
.build(); //構(gòu)建一個請求Request對象
//創(chuàng)建/Call
Call call = okHttpClient.newCall(request);
//加入隊列 異步操作
call.enqueue(new Callback() {
//請求錯誤回調(diào)方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("連接失敗");
}
//異步請求(非主線程)
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.code()==200) {
System.out.println(response.body().string());
}
});
POST(json方式)
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Book book = new Book();
book.setName("android基礎(chǔ)");
book.setPrice(59);
//使用Gson 添加 依賴 compile 'com.google.code.gson:gson:2.8.1'
Gson gson = new Gson();
//使用Gson將對象轉(zhuǎn)換為json字符串
String json = gson.toJson(book);
//MediaType 設(shè)置Content-Type 標(biāo)頭中包含的媒體類型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request request = new Request.Builder()
.url("http://172.20.192.168:8080/getbookByJson")//請求的url
.post(requestBody)
.build();
//創(chuàng)建/Call
Call call = okHttpClient.newCall(request);
//加入隊列 異步操作
call.enqueue(new Callback() {
//請求錯誤回調(diào)方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("連接失敗");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});
關(guān)于將對象轉(zhuǎn)換為json字符串,除了使用Gson還可以用JSONObject:
public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
try {
//example: {'likes':['體育','政治'...]}
jsonObject.put("likes",selectedThemes);
} catch (JSONException e) {
e.printStackTrace();
}
//創(chuàng)建一個RequestBody(參數(shù)1:數(shù)據(jù)類型 參數(shù)2傳遞的json串)
RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
開發(fā)過程中遇到傳json需要帶上authentication的問題,然后在Stack Overflow上找到了解決方法——使用Interceptor。
import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class BasicAuthInterceptor implements Interceptor {
private String credentials;
public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}
這樣就把username和password放進(jìn)了authentication里。然后把這個Interceptor加到OkHttpClient就可以了。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.build();
總結(jié)
以上是生活随笔為你收集整理的android get请求最长字符,Android OKHTTP3的GET和POST方法(带basic auth)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上海欢乐谷和上海迪士尼哪个大
- 下一篇: 牛肉哨子怎么做好吃呢?