您的位置:首页 > 理论基础 > 计算机网络

OkHttpUtils

2016-08-12 12:00 295 查看
OkHttpUtils工具类

package com.example.eggplant_doctor.util;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Map;

/**
* Created by Administrator on 2016/6/14.
*/
public class Okutil {

private static OkHttpClient client;

public static String getGet(String url) {

//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url(url)
.build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
try {
Response response = call.execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
public static String getGetGbk(String url) {

//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url(url)
.build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
try {
Response response = call.execute();
return new String(response.body().bytes(),"gbk");
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
public static String getPost(String url, Map<String, String> data) throws IOException {
client = new OkHttpClient();
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
for (Map.Entry<String, String> item : data.entrySet()) {
formBuilder.add(item.getKey(), item.getValue());
/* Log.i("key", item.getKey());
Log.i("values", item.getValue());*/
}

RequestBody body = formBuilder.build();
Request request = new Request.Builder().url(url).post(body).build();

Response response = excute(request);

if (response.isSuccessful()) {

return response.body().string();

} else {
throw new IOException("Unexpected code " + response);
}
}

private static Response excute(Request request) throws IOException {
return client.newCall(request).execute();
}

}


在类中调用

new Thread(new Runnable() {
@Override
public void run() {
String get = Okutil.getGet("http://www.hengboit.com/json/CourseInformation.json");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Gson g=new Gson();

}
});

}
}).start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  OkHttp