如何用AsyncHttpClient的post方法【发送JSON】

JSONObject body;是需要发送的json对象
getBodyTextAsJSON();方法可以将String转JSONObejct“`

private void sendPostWithJson(){
RequestParams params = new RequestParams();
params.setUseJsonStreamer(true);
JSONObject body;
if ((body = getBodyTextAsJSON()) != null) {
try {
Iterator keys = body.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Log.d(“hwj”, ” ” + key + “: ” + body.get(key));
params.put(key, body.get(key).toString());
}
} catch (JSONException e) {
Log.w(“hwj”, “Unable to retrieve a JSON value”, e);
}
}
AsyncHttpClient client = new AsyncHttpClient();
client.setProxy(“172.29.14.249”,8888);
client.post(this, “http://112.4.3.136:8080/portalone/homesdk/NetTVUniLogin“, null, params,
RequestParams.APPLICATION_JSON,new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
Log.d(“hwj”, “AsyncHttpClientActivity onSuccess“);
}

        @Override
        public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
            Log.d("hwj", "**AsyncHttpClientActivity onFailure**");
        }
    });
}

protected JSONObject getBodyTextAsJSON() {
    String bodyText = "{\n" +
            "\"employees\": [\n" +
            "{ \"firstName\":\"Bill\" , \"lastName\":\"Gates\" },\n" +
            "{ \"firstName\":\"George\" , \"lastName\":\"Bush\" },\n" +
            "{ \"firstName\":\"Thomas\" , \"lastName\":\"Carter\" }\n" +
            "]\n" +
            "}";
    if (bodyText != null && !TextUtils.isEmpty(bodyText)) {
        try {
            return new JSONObject(bodyText);
        } catch (JSONException e) {
            Log.e("hwj", "User's data is not a valid JSON object", e);
        }
    }
    return null;
}

“`
更多的sample这边就不一一列举了,可以参考如下地址 asynchttpclient样例

该方法来源于 【彻底掌握网络通信(十)】

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭