今天主要來應用okhttp的這個套件,與Retrofit、HttpUrlConnection等雷同,都是可進行連線取回資料並解析,執行取傳值的動作,那麼今天主要要透過假資料網站來做,那麼就開始介紹,首先先添加需要的權限以及依賴。
因為會用到網路,所以添加網路的權限至Manifest中。
<uses-permission android:name="android.permission.INTERNET" />
將okhttp需要的依賴加入至gradle中。
implementation 'com.squareup.okhttp3:okhttp:4.7.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.7.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.7.0'
透過使用Okhttp進行連線至少會使用到以下三個物件:
private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30,TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.addHeader("Content-Type","application/json")
.get()
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response){
//連線成功,取得回傳response
}
@Override
public void onFailure(Call call, IOException e) {
//當連線失敗
}
});
那麼接著來設計程式,今天主要加入了兩顆按鈕,一顆用來做POST而另一顆做GET,這兩個差最多在Request資料的建置上,post需要多寫入一個json body的資料,而最後將這兩個結果進行Log來顯示。
public class MainActivity extends AppCompatActivity {
//建立連線基底,並加入Interceptor(攔截器)
private OkHttpClient okHttpClient =new OkHttpClient().newBuilder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)).build();
private TextView txv;
private Button btn_get,btn_post;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv=findViewById(R.id.textView);
btn_get=findViewById(R.id.btn_get);
btn_post=findViewById(R.id.btn_post);
btn_get.setOnClickListener(view->{
//連線資訊建立
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
//call執行request
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response){
try {
String result = response.body().string();
Log.d("Response",""+result);
} catch (Exception e) {
Log.d("Error",""+e);
}
}
@Override
public void onFailure(Call call, IOException e) {
Log.d("OkHttp Error:", e.getMessage());
}
});
});
btn_post.setOnClickListener(view->{
FormBody formBody=new FormBody.Builder() //FormBody設置(用來post的資料
.add("UserId","101")
.add("id","101" )
.add("title","this is title")
.add("body","this is body")
.build();
Request request =new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts")
.post(formBody) //將資料寫入
.build();
Call call =okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("OkHttp result:", e.getMessage());
}
@Override
public void onResponse(Call call, Response response){
try {
String result = response.body().string();
Log.d("Response",""+result);
} catch (Exception e) {
Log.d("Error",""+e);
}
}
});
});
}
}