标签:android style blog http io os 使用 ar java
采用HttpClient与远程服务器通信,所以定义一个工具类对HttpClient进行封装
getRequest():发送get请求
postRequest():发送post请求
FutureTask(Callable<V> callable) //创建一个 FutureTask,一旦运行就执行给定的 Callable。
FutureTask(Runnable runnable, V result) //创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时 get 返回给定的结果 。
FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。
public class HttpUtil
{
// 创建HttpClient对象
public static HttpClient httpClient = new DefaultHttpClient();
public static final String BASE_URL =
"http://192.168.1.88:8888/auction/android/";
/**
*
* @param url 发送请求的URL
* @return 服务器响应字符串
* @throws Exception
*/
public static String getRequest(final String url)
throws Exception
{
FutureTask<String> task = new FutureTask<String>(
new Callable<String>()
{
@Override
public String call() throws Exception
{
// 创建HttpGet对象。
HttpGet get = new HttpGet(url);
// 发送GET请求
HttpResponse httpResponse = httpClient.execute(get);
// 如果服务器成功地返回响应
if (httpResponse.getStatusLine()
.getStatusCode() == 200)
{
// 获取服务器响应字符串
String result = EntityUtils
.toString(httpResponse.getEntity());
return result;
}
return null;
}
});
new Thread(task).start();
return task.get();
}
/**
* @param url 发送请求的URL
* @param params 请求参数
* @return 服务器响应字符串
* @throws Exception
*/
public static String postRequest(final String url
, final Map<String ,String> rawParams)throws Exception
{
FutureTask<String> task = new FutureTask<String>(
new Callable<String>()
{
@Override
public String call() throws Exception
{
// 创建HttpPost对象。
HttpPost post = new HttpPost(url);
// 如果传递参数个数比较多的话可以对传递的参数进行封装
List<NameValuePair> params =
new ArrayList<NameValuePair>();
for(String key : rawParams.keySet())
{
//封装请求参数
params.add(new BasicNameValuePair(key
, rawParams.get(key)));
}
// 设置请求参数
post.setEntity(new UrlEncodedFormEntity(
params, "gbk"));
// 发送POST请求
HttpResponse httpResponse = httpClient.execute(post);
// 如果服务器成功地返回响应
if (httpResponse.getStatusLine()
.getStatusCode() == 200)
{
// 获取服务器响应字符串
String result = EntityUtils
.toString(httpResponse.getEntity());
return result;
}
return null;
}
});
new Thread(task).start();
return task.get();
}
}
标签:android style blog http io os 使用 ar java
原文地址:http://www.cnblogs.com/zhujiabin/p/3997170.html