/**
* 使用异步http框架发送get请求
*
* @param path get路径,中文参数需要编码(URLEncoder.encode)
*/
public void doGet(String path) {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (statusCode == 200) {
try {
//此处应该根据服务端的编码格式进行编码,否则会乱码
System.out.println("Post:"+new String(responseBody, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
System.out.println("-------Error-------");
}
});
}
/**
* 使用异步http框架发送get请求
*
* @param path
*/
public void doPost(String path) {
AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("", "");//value可以是流、文件、对象等其他类型,很强大!!
httpClient.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (statusCode == 200) {
try {
//此处应该根据服务端的编码格式进行编码,否则会乱码
System.out.println("Get:"+new String(responseBody, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
System.out.println("-------Error-------");
}
});
}
Android 学习记录(一):发送 http 请求
------ 本文结束------