0
這裏後是情景:我有一個活動,命名爲MainActivity
,調用OkHttp包裝類,命名NetworkManager
在後臺進行網絡帖子:OkHttp觸發回調的起源類整理的網絡行爲
// In MainActivity
NetworkManager manager = new NetworkManager();
try {
manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject
} catch(IOException ioe) {
Log.e(TAG, ioe.getMessage());
}
然後,在NetworkManager
,我執行異步模式POST操作:
public class NetworkManager {
static String TAG = "NetworkManager";
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
void post(String url, JSONObject json) throws IOException {
//RequestBody body = RequestBody.create(JSON, json);
try {
JSONArray array = json.getJSONArray("d");
RequestBody body = new FormEncodingBuilder()
.add("m", json.getString("m"))
.add("d", array.toString())
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// Asynchronous Mode
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.e(TAG, e.toString());
// what should I put here?
}
@Override
public void onResponse(Response response) throws IOException {
Log.w(TAG, response.body().string());
// what should I put here?
}
});
} catch (JSONException jsone) {
Log.e(TAG, jsone.getMessage());
}
}
}
我試圖做到的,是調用一個函數在MainActivity
後網絡帖子是成功還是失敗。我怎樣才能做到這一點?
雖然我沒有試過OkHttp您的問題,然而,國際海事組織,這是同樣的方式與排球,因此,請閱讀以下一些環節:http://stackoverflow.com/questions/33535435/how-to-創建一個適當的排球監聽器爲交叉類排球方法調用/ 33535554#33535554 http://stackoverflow.com/questions/31602042/android-java-how-to-delay-return-in -a-method和http://stackoverflow.com/questions/32375295/android-how-to-return-async-jsonobject-from-method-using-volley/32379539#32379539。我認爲@約翰的答案在下面爲你的問題:) – BNK