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

你可能感兴趣的:(http,android,android,HtppPost)