我正在尋找解決方案來使用OKHTTP實現JSON-POST請求。我有一個處理所有方法(POST,GET,PUT,DELETE)的HTTP-Client.java文件,並且在RegisterActivity中我想將用戶數據(從輸入字段)POST到JSON格式的服務器。使用OKHTTP進行Android JSON POST
這是我HTTP-Client.java
public class HttpClient{
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public static OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
public static Call post(String url, String json, Callback callback) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body.create(JSON, json))
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
...這是從RegisterActivity
btnRegRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO
String registerData = "{\"email\":\"" + etRegisterEmail.getText().toString() + "\",\"password\":\"" + etRegisterPasswort.getText().toString() + "\"}";
try {
HttpClient.post(ABSOLUTE_URL, registerData, new Callback(){
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String resp = response.body().string();
if (resp != null) {
Log.d("Statuscode", String.valueOf(response.code()));
Log.d("Body", response.body().string());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
每次我開始崩潰的應用程序中的onClick - 第一部分當我點擊註冊按鈕造成的致命錯誤'android.os.NetworkOnMainThreadException'
我已經讀了一些關於AsyncTask的內容,但我不知道如何做到這一點。
首先,請使用okhttp和GSON查看Retrofit。對於高級版本,您可以使用Otto和Dagger2將核心業務與前端完全分開。 – bajicdusko