OkHttp 使用 2018 11 12
private MyHttp() {
}
public static MyHttp ob;
public static MyHttp getInstance() {
if (ob == null) {
return new MyHttp();
} else {
return ob;
}
}
public void HttpGet(final String url, final ResultBack callback) {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
callback.success(response.body().string());
} catch (IOException e) {
e.printStackTrace();
callback.failed(e.getMessage());
}
}
}).start();
}
public void HttpPost(final String url, final Map data, final ResultBack callback) {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder builder = new FormBody.Builder();
for (Object key : data.keySet()) {
String keyTme= (String) key;
builder.add(keyTme,data.get(keyTme).toString());
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
callback.success(response.body().string());
} catch (IOException e) {
callback.failed(e.getMessage());
}
}
}).start();
}
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");// 請求頭
public void HttpJsonPost(final String url, final String jsonBody, final ResultBack callback) {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = RequestBody.create(JSON,jsonBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
callback.success(response.body().string());
} catch (IOException e) {
callback.failed(e.getMessage());
}
}
}).start();
}
public void HttpJson(final String url, final Map<String,String > jsonBody, final ResultBack callback) {
Log.e("okhttp" ,""+url) ;
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)//設定連線超時時間
.readTimeout(20, TimeUnit.SECONDS)//設定讀取超時時間
.build();
String bodya = new Gson().toJson(jsonBody);
RequestBody body = RequestBody.create(JSON,bodya);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
callback.success(response.body().string());
} catch (IOException e) {
if (e instanceof SocketTimeoutException){
// 超時異常
callback.failed(e.getMessage());
}
if (e instanceof ConnectException){
//連線異常
callback.failed(e.getMessage());
}
callback.failed(e.getMessage());
}
}
}).start();
}
compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.okio:okio:1.11.0'