访问接口工具类
public class NetTool {
// FormBody body = new FormBody.Builder() .add("userPwd", "123").build();
public static void netPost(final Handler handler, final String url, final FormBody body, final NetBack netBack) {
new Thread() {
@Override
public void run() {
try {
Request request = new Request.Builder().url(url).post(body).build();
Response response = new OkHttpClient().newCall(request).execute();
final String result = response.body().string();
Log.i("MyThread", "result:" + result);
handler.post(new Runnable() {//运行到Ui线程
@Override
public void run() {
netBack.onBack(result);
}
});
} catch (Exception e) {
Log.i("MyThread", "Exception:" + e);
e.printStackTrace();
}
}
}.start();
}
public interface NetBack {
void onBack(String json);//
}
}
访问网络
Handler handler = new Handler(){};
private void f(String url) {
FormBody body = new FormBody.Builder().build();
NetTool.netPost(handler, url, body, new NetTool.NetBack() {
@Override
public void onBack(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
String status = jsonObject.getString("status");
if (status.equals("success")) {
String msg = jsonObject.getString("msg");
} else {
Toast.makeText(context, "网络错误!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
记得在AndroidManifest.xml文件中添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />