1.volley
依赖:implementation 'com.android.volley:volley:1.1.1'
网络权限:<uses-permission android:name="android.permission.INTERNET"/>
get请求:
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
jsonData = response;
button.setClickable(true);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
post请求:
String url = "https://api.inews.qq.com/newsqa/v1/automation/foreign/country/ranklist";
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject object = new JSONObject();
try {
object.put("name", "123");
object.put("pass", "123456");
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("凉城", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(objectRequest);
queue.start();
} catch (JSONException pE) {
pE.printStackTrace();
}
2.okhttp
依赖:implementation 'com.squareup.okhttp3:okhttp:3.2.0'
String url = "https://www.wanandroid.com/project/tree/json";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
final Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("凉城data失败", e.getMessage());
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String string = response.body().string();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
InfoBean infoBean = new Gson().fromJson(string, InfoBean.class);
mAdapter.setBeans(infoBean.getData());
}
});
}
});
3.Retrofit
依赖:implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.foodUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<FoodBean> food = apiService.getFood("20", "1");
food.enqueue(new Callback<FoodBean>() {
@Override
public void onResponse(Call<FoodBean> call, Response<FoodBean> response) {
FoodBean body = response.body();
Log.d(TAG, "onResponse: " + body.toString());
}
@Override
public void onFailure(Call<FoodBean> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.getMessage());
}
});
ApiService:
public static final String foodUrl="http://www.qubaobei.com/ios/";
@GET("cf/dish_list.php?stage_id=1&")
Call<FoodBean> getFood(@Query("limit")String limit,@Query("page")String page);