OKHttp的使用GET和POS 请求方式,处理json数据

在使用OKHttp之前我们需要添加依赖库,


compile 'com.squareup.okhttp3:okhttp:3.8.1'


直接上代码

-----------------------------------------------------------------------------------------------------------------------------------

Get请求 如下

public static  String getHttp(){
    // 请求的url地址
    String url = "";
    //创建okHttpClient对象
    OkHttpClient httpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .build();
    try {
        Response response = httpClient.newCall(request).execute();
        if(response.isSuccessful()){
            //使用JSONObject 处理结果
            JSONObject jsonObject = new JSONObject(response.body().string());

            Log.i("---",jsonObject.toString());

            return status;

        }
    } catch (IOException e) {
        Log.i("---", e.toString());
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return "";
}



POST请求 参数为json类型


// 请求头设置
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static String postHttp(){
    // 请求的url地址
    String url = "";
    //创建okHttpClient对象
    OkHttpClient httpClient = new OkHttpClient();
    JSONObject json =new JSONObject();
    try {
        json.put("op","install");
        json.put("game","123");
        json.put("device","123");
        json.put("identifier","123");
        // 第一个参数JSON 为请求头设定 ,第二个参数为携带的参数
        RequestBody body = RequestBody.create(JSON,json.toString());
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()){
            JSONObject jsonObject = new JSONObject(response.body().string());
            Log.i("---",jsonObject.toString());
        }

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    return "";
}





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值