Android提交请求到服务器

Android开发中经常需要提交请求到服务器,这里简单的封装了一个NetUtil.java类:

<pre name="code" class="java">package com.zemo.campus.tools;

</pre><pre name="code" class="java">import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;//访问服务器public class NetUtils {/** * 请求服务器,并返回服务器返回的值 * * @param serverurl * 服务器的地址 * @param method * 请求服务器所使用的请求方法 * @param params * 请求参数 * @return 服务器返回给浏览器的值 */public static String con2Server(String serverurl, String method,Map<String, String> maps) throws Exception {String result = null;HttpClient client = new DefaultHttpClient();HttpResponse response=null;if ("get".equalsIgnoreCase(method)) {if (maps != null) {// 参数不为null,说明有参数serverurl += "?";for (Map.Entry<String, String> me : maps.entrySet()) {String key = me.getKey();String value = me.getValue();serverurl = serverurl + key + "=" + value + "&";}// 去掉最后一个&,substring参数包括开始的索引不包括最后一个serverurl.substring(0, serverurl.length() - 1);}HttpGet httpGet = new HttpGet(serverurl);response = client.execute(httpGet);} else if ("post".equalsIgnoreCase(method)) {List<NameValuePair> parameters = null;// 准备参数if (maps != null) {parameters = new ArrayList<NameValuePair>();for (Map.Entry<String, String> me : maps.entrySet()) {String key = me.getKey();String value = me.getValue();parameters.add(new BasicNameValuePair(key, value));}}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");HttpPost httpPost = new HttpPost(serverurl);// 设置post请求的数据实体httpPost.setEntity(entity);response = client.execute(httpPost);}// 发送数据到服务器int code = response.getStatusLine().getStatusCode();if (code == 200) {InputStream is = response.getEntity().getContent();byte[] bytes = StreamTool.getBytes(is);result = new String(bytes, "utf-8");}return result;}}
 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值