android http类,android的 Http工具类

android的HttpClient实现简单的get和post请求

/**

* Http工具类

*/

public class HttpUtil {

// 创建HttpClient对象

public static HttpClient httpClient = new DefaultHttpClient();

public static final String BASE_URL = "";

/**

* get请求

*

* @param url

* 发送请求的URL

* @return 服务器响应字符串

* @throws Exception

*/

public static String doGet(String url) throws Exception {

// 创建HttpGet对象。

HttpGet get = new HttpGet(url);

// 发送GET请求

HttpResponse httpResponse = httpClient.execute(get);

// 如果服务器成功地返回响应

if (httpResponse.getStatusLine().getStatusCode() == 200) {

// 获取服务器响应字符串

HttpEntity entity = httpResponse.getEntity();

InputStream content = entity.getContent();

return convertStreamToString(content);

}

return null;

}

/**

* post请求

*

* @param url

* 发送请求的URL

* @param params

* 请求参数

* @return 服务器响应字符串

* @throws Exception

*/

public static String doPost(String url, Map rawParams)

throws Exception {

// 创建HttpPost对象。

HttpPost post = new HttpPost(url);

// 如果传递参数个数比较多的话可以对传递的参数进行封装

List params = new ArrayList();

for (String key : rawParams.keySet()) {

// 封装请求参数

params.add(new BasicNameValuePair(key, rawParams.get(key)));

}

// 设置请求参数

post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

// 发送POST请求

HttpResponse httpResponse = httpClient.execute(post);

// 如果服务器成功地返回响应

if (httpResponse.getStatusLine().getStatusCode() == 200) {

// 获取服务器响应字符串

HttpEntity entity = httpResponse.getEntity();

InputStream content = entity.getContent();

return convertStreamToString(content);

}

return null;

}

/**

* 获取服务器的响应,转换为字符串

*/

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

StringBuilder sb = new StringBuilder();

String line = null;

try {

while ((line = reader.readLine()) != null) {

sb.append(line);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return sb.toString();

}

}

标签:

服务器

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值