1、post请求发送json字符串:
AsyncHttpClient client = new AsyncHttpClient();
Context context = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "ryantang");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
client.post(context, "http://api.com/login", stringEntity,
"application/json", new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
super.onSuccess(jsonObject);
}
});
} catch (Exception e) {
e.printStackTrace();
}
在服务端,直接使用以下代码得到json数据:
String content = IOUtils.toString(request.getInputStream());
System.out.println(content);
打印的日志如下:
{"username":"ryantang"}
2、上传文件及参数:
final File zipFile = new File(logFile.getParentFile()
.getAbsolutePath()
+ File.separatorChar
+ System.currentTimeMillis() + IMEI + ".zip");
RequestParams params = new RequestParams();
try {
ZipUtils.zipFiles(historyLogs, zipFile);
params.put("userid", userId);
params.put("phone_no", phoneNo);
params.put("os_descript", OSDESCRIPT);
params.put("os_version", OSVER);
params.put("oem", OEM);
params.put("version_id", String.valueOf(versionCode));
params.put("version_name", versionName);
params.put("package_name", packageName);
params.put("app_name", appName);
params.put("file", zipFile);//文件
} catch (IOException e) {
e.printStackTrace();
}
new AsyncHttpClient().post(serviceUrl, params,
new AsyncHttpResponseHandler() {
@Override
public void onFinish() {
Log.i("uploadHistory", "onFinish");
zipFile.delete();
super.onFinish();
}
@Override
public void onStart() {
Log.i("uploadHistory", "onStart");
super.onStart();
}
@Override
public void onSuccess(String content) {
Log.i("uploadHistory", "onSuccess" + content);
for (Map.Entry<String, File> file : historyLogs
.entrySet()) {
if (!file.getKey().equals(logFile.getName())) {
file.getValue().delete();
}
}
super.onSuccess(content);
}
});
3、get请求:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.baidu.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
textView.setText(response);
}
@Override
public void onStart() {
super.onStart();
System.out.println("onStart");
}
@Override
public void onFinish() {
super.onFinish();
System.out.println("onFinish");
}
}