第一种方式请求 get
private void xu() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Gson gson = new Gson(); DataBean dataBean = gson.fromJson(string, DataBean.class); datalist.addAll(dataBean.getReturnValue()); runOnUiThread(new Runnable() { @Override public void run() { myAdapter.notifyDataSetChanged(); } }); } }); }
第二种方式 post 带键值对
private static void httpPost() {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody body = new FormBody.Builder()
.add("xxxx", "xxx")
.build();
Request request = new Request.Builder().post(body).url("").build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
}
});
}
第三种 post 不带键值对
public static void postRequestMallPoint(String url, final String jsonContent) {
OkHttpClient mOkHttpClient = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonContent);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
Log.i("ysq", "shibai");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
Log.i("ysq", str);
}
});
}