Android Http通信

  Http的方式通信,下面看看它的过程:

1、传入URL,实例化HtppPost。Http通信当然是Web通信,就要一个网址了,即HttpPost httpRequest = new HttpPost(String URL);
 2、发送参数(无参、带参)。这里有两种方法:Get/Post方法,选择用哪个我相信大家都知道,即先传参httpRequest.setEntity(httpentity),
   再发送new DefaultHttpClient().execute(httpRequest);
 3、得到服务器所调用方法的结果。前面传了个参,同理,服务器要返回个参数,即EntityUtils.toString(httpResponse.getEntity());

 
 OK,就这么简单,httpPost还要设置头消息,httpPost.addHeader("Content-Type", "application/json;charset=utf-8");当然,还要网络的访问权限<uses-permission android:name="android.permission.INTERNET" />,下面附上主要代码:
    

httpHelper = new HttpHelper(Serverip);

 List<NameValuePair> List = new ArrayList<NameValuePair>();
 List.clear();


 runServce(FinalAction.NO_PARA, List);


 public String runServce(String servceAction, List<NameValuePair> sList) {
  String result = null;
  String ParValue = null;
  String ParName = null;
  try {
   HttpPost httpPost = new HttpPost(servceURL(servceAction));

   if (sList != null && sList.size() > 0) {
    JSONObject sendParams = new JSONObject();
    for (int i = 0; i < sList.size(); i++) {
     ParName = sList.get(i).getName();
     ParValue = sList.get(i).getValue();
     sendParams.put(ParName, ParValue);
    }
    String send = sendParams.toString();
    HttpEntity entity = new StringEntity(send, "UTF-8");
    httpPost.setEntity(entity);
   }
   
   httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
   HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);

   if (httpResp.getStatusLine().getStatusCode() == 200) {
    Log.d("HttpPost",EntityUtils.toString(httpResponse.getEntity()));
   }else {
    Log.i("", "请求失败!");
            }

  } catch (Exception ee) {
   ee.printStackTrace();
  }
  return result;
 }



  我的博客其它文章列表  
   http://my.oschina.net/helu

转载于:https://my.oschina.net/helu/blog/141716

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值