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

来源:互联网 发布:复制的链接在淘宝打开 编辑:程序博客网 时间:2024/06/08 01:57

在使用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 "";}





原创粉丝点击