Post和Get在http中的使用

来源:互联网 发布:ic卡发卡软件 编辑:程序博客网 时间:2024/05/19 06:16

HttpClient入门

http://www.ibm.com/developerworks/cn/opensource/os-httpclient/

Class PostMethod

http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/PostMethod.html



HttpClient提供的主要功能如下:

    实现了所有Http的方法(GET,POST,PUT,HEAD)等

    支持自动转向

    支持Https协议

    支持代理服务器

HTTP方法中最常用的是POST和GET方法

  GET方法要求服务器将URL定位的资源放在相应的报文的数据部分,回送给客户端。使用Get方法时将请求的参数和对应值附在URL后面,利用一个问号(?)

代表URL的结束和请求参数的开始。

       通过get获取页面信息,返回输出流

      public static InputStream getInputStreamFromUrl(String URL){

              InputStream conntent= null;

             try{

                     HttpClient httpClient = new DefalutHttpClient();

                     HttpResponse response = httpClient.excute(new HttpGet(URL));

                     content = response.getEntity().getContent;

             }catch{

                      }

            return conntent;

           }

        将输出流InputStream转化成StringBuilder格式

      private StringBuilder inputStreamToStringBuider(InputStream is){

          String line = “”;

          StringBuilder total =  new StringBuilder();

          BufferedReader rd = new BufferedReader(new InputStreamReader(is));

          while((line = rd.readLine()!=null)){

                      total.append(line);

          }

         return total;

     }

      将InputStream格式数据流转换为String格式

    

      private String inputStreamToString(InputStream is){

          String line = “”;

          String  total =  “”;

          BufferedReader rd = new BufferedReader(new InputStreamReader(is));

          while((line = rd.readLine()!=null)){

                      total += line;

          }

         return total;

     }

      POST方法要求被请求服务器接收附在请求后面的数据,常用于提交表单。POST方法将求求参数封装在HTTP请求数据中,以名称值得形式出现,可以传输大量数据。

     public void postData(){

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(http://www.google.com);

        try{

            list<NameValuePair> namValuePair = new ArrayList<NameValuePair>;new

           nameValuePair.add(new BsicNameValuePair("id","12345"));

           nameValuePair.add(new BsicNameValuePair("stringdata","myString"));

           httpPost.setEntity(new UriEncodeFormEntity(nameValuePair,"UTF-8"));

           HttpResponse response = httpClient.excute(httpPost);

          }catch(ClientPotocalException e){

        

        }catch(IOException e){

         

         }

      }

1.  创建HttpClient




0 0
原创粉丝点击