赞
踩
dependencies {
api 'com.squareup.okhttp3:okhttp:3.14.0'
}
<uses-permission android:name="android.permission.INTERNET" />
public static String get(String url) {
Request request = new Request.Builder().url(url).build();
try {
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
Log.d("success", result.toString());
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("fail", "返回参数为空 !");
return null;
}
GET的调用方法:
new Thread(new Runnable() {
@Override
public void run() {
try {
String result = CommonCode.get(requestURL);
//此处根据需要对返回的json字符串进行处理解析。
} catch (Exception e) {
Log.d("failure", "run: " + e.toString());
}
}
}).start();
static String post(JSONObject param, String url){ RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), param.toString()); try{ Request request = new Request.Builder().url(url).post(requestBody).build(); try (Response response = okHttpClient.newCall(request).execute()) { String result = response.body().string(); if (null == result || "".equals(result)){ throw new Exception("返回了一个空值!"); } return result; }catch (Exception e){ throw e; } }catch (Exception e){ Log.d(TAG, "post: post请求失败:" + e); String result = "{'flag':0,'message':'" + e.toString() + "'}"; return result; } }
POST的调用方法:
new Thread(new Runnable() {
@Override
public void run() {
JSONObject param = new JSONObject();
try {
param.put(key, vanlue); //挨个put你的参数
String result = CommonCode.post(param, serverAddress);
} catch (Exception e) {
Log.d("failure", "run: " + e.toString());
}
}
}).start();
public static JSONArray postGetJsonArray(JSONObject param, String url) {
String resultstr = post(param,url);
JSONArray result = JSONArray.parseArray(resultstr);
return result;
}
public static JSONObject postGetJson(JSONObject param, String url) {
String resultstr = post(param,url);
try{
JSONObject result = JSONObject.parseObject(resultstr);
return result;
}catch (Exception e){
JSONObject failed = new JSONObject();
failed.put(Constants.Param.RESULT_FLAG,0);
failed.put(Constants.Param.RESULT_MESSAGE,e.toString());
return failed;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。