package com.create.qdocumentimtest.rxjavatest;
import com.squareup.okhttp.Callback;
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.HashMap;
import java.util.Objects;
/**
* Created by Administrator on 2016/6/7 0007.
*/
public class HttpHelper {
String baseUrl = "";
private OkHttpClient okhttp = new OkHttpClient();
private String url;
public HttpHelper(String url) {
this.url = url;
}
/**
* get请求 同步方法
*
* @return
*/
public String requestByGetSync() {
Request request = new Request.Builder().url(url).build();
try {
Response response = okhttp.newCall(request).execute();//同步请求
if (!response.isSuccessful()) {
throw new IOException("Unexpected code" + response);
}
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* get请求 异步
*
* @param callback
* @return
*/
public void requestByGetAsync(Callback callback) {
Request request = new Request.Builder().url(url).build();
okhttp.newCall(request).equals(callback);
}
/**
* post异步
*
* @param callback
*/
public void requestByPostAsync(HashMap<String, Objects> map, Callback callback) {
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
for (String key : map.keySet()) {
formEncodingBuilder.add(key, map.get(key) + "");
}
RequestBody body = formEncodingBuilder.build();
Request request = new Request.Builder()
.url(baseUrl + url)
.post(body)
.build();
okhttp.newCall(request).enqueue(callback);
}
/**
* post 同步请求
* @param map
* @return
*/
public String requestByPostSync(HashMap<String, Objects> map) {
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
for (String key : map.keySet()) {
formEncodingBuilder.add(key, map.get(key) + "");
}
RequestBody body = formEncodingBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
try {
response = okhttp.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}