程序员

Okhttp 发送数据 请求解析 方法实现

2019-03-29  本文已影响8人  小明同学机器人

okhttp请求网络 发送请求 取到数据的方法

用到的jar包

public class NetUtil {

//同步传输  用于实现发送JSon等数据  请求结果

    public static String getData(String url, String data) {

String result ="";

Log.i("发送的数据","getData: " + data);

OkHttpClient okHttpClient =new OkHttpClient();

RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), data);

Request request =new Request.Builder().post(requestBody).url(url).build();

try {

Response response = okHttpClient.newCall(request).execute();

result = response.body().string();

Log.i("接收的数据","getData: " + result);

return result;

}catch (IOException e) {

Log.i("接收失败","getData: " + result);

e.printStackTrace();

}

return result;

}

//异步传输  用于实现发送JSon等数据  请求结果

    public static synchronized void getData(String url, String data, Callback callback) {

Log.i("发送的数据","getData: " + data);

OkHttpClient okHttpClient =new OkHttpClient();

RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), data);

Request request =new Request.Builder().post(requestBody).url(url).build();

okHttpClient.newCall(request).enqueue(callback);

}

}

上一篇下一篇

猜你喜欢

热点阅读