Http连接GET/POST请求

来源:互联网 发布:java游戏小程序贪吃蛇 编辑:程序博客网 时间:2024/04/28 05:37
原地址:http://blog.csdn.net/sjf0115/article/details/7385125
创建步骤:
  1、创建HttpGet(或HttpPost)对象,将要请求的URL通过构造方法传入HttpGet(或HttpPost)对象中;
   2、使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST 请求,并返回HttpResponse对象;
   3、通过HttpResponse接口的getEntity方法返回响应信息。

Http连接POST请求

[java] view plaincopy
  1. // 第一步,创建HttpPost对象  
  2.         HttpPost httpPost = new HttpPost(url);  
  3.         // 设置HTTP POST请求参数必须用NameValuePair对象  
  4.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  5.         params.add(new BasicNameValuePair("bookname""2465158248"));  
  6.         System.out.println("result1");  
  7.         // 设置httpPost请求参数  
  8.         try  
  9.         {  
  10.             httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  11.             // 第二步,使用execute方法发送HTTP GET请求,并返回HttpResponse对象  
  12.             HttpResponse httpResponse;  
  13.             try  
  14.             {  
  15.                 httpResponse = new DefaultHttpClient().execute(httpPost);  
  16.                 System.out.println("result");  
  17.                 if (httpResponse.getStatusLine().getStatusCode() == 200)  
  18.                 {  
  19.                     // 第三步,使用getEntity方法活得返回结果  
  20.                     String result = EntityUtils.toString(httpResponse.getEntity());  
  21.                     System.out.println("result" + result);  
  22.                 }  
  23.             }  
  24.             catch (ClientProtocolException e)  
  25.             {  
  26.                 // TODO Auto-generated catch block  
  27.                 e.printStackTrace();  
  28.             }  
  29.             catch (IOException e)  
  30.             {  
  31.                 // TODO Auto-generated catch block  
  32.                 e.printStackTrace();  
  33.             }  
  34.         }  
  35.         catch (UnsupportedEncodingException e)  
  36.         {  
  37.             e.printStackTrace();  
  38.         }  
  39.     }  

Http连接GET请求
[java] view plaincopy
  1. String url;  
  2.   //第一步,创建HttpGet对象  
  3.   HttpGet httpGet = new HttpGet(url);  
  4.   //第二步,使用execute方法发送HTTP GET请求,并返回HttpResponse对象  
  5.   httpResponse = new DefaultHttpClient().execute(httpGet);  
  6.   if (httpResponse.getStatusLine().getStatusCode() == 200)  
  7.   {  
  8.        //第三步,使用getEntity方法活得返回结果  
  9.        String result = EntityUtils.toString(httpResponse.getEntity());  
  10.    } 

原创粉丝点击