码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient 实现POST请求

时间:2016-06-17 11:02:52      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:

String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
 /*
    * NameValuePair代表一个HEADER,List<NameValuePair>存储全部的头字段
    * UrlEncodedFormEntity类似于URLEncoder语句进行URL编码
    * HttpPost类似于HTTP的POST请求
    * client.execute()类似于发出请求,并返回Response
 */  

  // HttpPost连接对象
  HttpPost httpRequest = new HttpPost(httpUrl);
  // 使用NameValuePair来保存要传递的Post参数
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  // 添加要传递的参数

  NameValuePair pair1 = new BasicNameValuePair("par", "HttpClient_android_Post"));
  params.add(pair1);
  //params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
  try 
  {
   // 设置字符集
   HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
   // 请求httpRequest
   httpRequest.setEntity(httpentity);
   // 取得默认的HttpClient
   HttpClient httpclient = new DefaultHttpClient();
   // 取得HttpResponse
   HttpResponse httpResponse = httpclient.execute(httpRequest);
   // HttpStatus.SC_OK表示连接成功
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  {
     // 取得返回的字符串
     String strResult = EntityUtils.toString(httpResponse.getEntity());
     mTextView.setText(strResult);
    } 
  else {
     mTextView.setText("请求错误!");
    }
  } 
catch (ClientProtocolException e) {
    mTextView.setText(e.getMessage().toString());
  } 
catch (IOException e) {
    mTextView.setText(e.getMessage().toString());
  } 
catch (Exception e){
    mTextView.setText(e.getMessage().toString());
 }

 

HttpClient 实现POST请求

标签:

原文地址:http://www.cnblogs.com/xiaoluoluo/p/5593294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!