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