Http Get
直接上代码:
//创建okHttpClient对象
OkHttpClient mClient = new OkHttpClient();
//创建一个Request
Request request = new Request.Builder()
.url("http://...")
.build();
Call call = mClient.newCall(request);
//请求加入调度
call.enqueue(new Callback()
{
@Override//失败
public void onFailure(Request request, IOException e)
{
}
@Override//成功
public void onResponse(final Response response) throws IOException
{
}
});
Http Post 携带参数
附加成功请求后接受服务器端的数据
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
FormBody formBody = new FormBody.Builder()
.add("a", "facedata")
.add("b", “哈哈哈”)
.build();
final Request request = new Request.Builder()
.url("http://192.168.43.72:8000/post/")//请求的url
.post(formBody)
.build();
//创建/Call
Call call = okHttpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.code()==200) {
String s=response.body().string();
System.out.println(s);
try{
/*
JSONArray jsonArray=new JSONArray(s);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String a=jsonObject.getString("a");
String b=jsonObject.getString("b");
}*/
JSONObject jsonObject=new JSONObject(s);
String a=jsonObject.getString("a");
String b=jsonObject.getString("b");
}catch (Exception e){
e.printStackTrace();
}
}
}
});