httpclient發送不帶參數post數據


兩個問題:
     1、httpclient怎樣發送一個沒有不論什么參數的post數據呢?
     2、Webproject怎樣去接收一個無參數的post呢?

起因:
     今天(2014.11.10)在開發中碰到了一個問題。接口提供方提供的接口是要求使用post方式發送數據的。心想這不超簡單的一個東西嗎?直接post過去不就是了。可是,提供的接口是沒有不論什么參數的。不是類似這樣的http://api.dutycode.com/data/parm=xxx這樣的接口,而是http://api.dutycode.com/data。這個地址直接接收post數據。
     話說,當時瞬間心碎了,沒接觸過啊。。。

     可是,總歸是有解決的方法的。既然有這種接口來接收數據,那么一定能夠發送
so

解決的方法:非常easy
     實現代碼例如以下:
     
public   static  void  main(String[] args)  throws  Exception {
            HttpClient client = HttpClients. createDefault();
            
            HttpPost post =  new  HttpPost( "http://127.0.0.1/report/testPost"  );
            
              //組裝一個 json串。用於發送
            JSONObject jsonObj =  new  JSONObject();
            jsonObj.put(  "website"   "http://www.dutycode.com"  );
            jsonObj.put(  "email"   "dutycode@gmail.com"  );
            
            StringEntity entity =  new  StringEntity(jsonObj.toJSONString());
            entity.setContentEncoding(  "UTF-8"  );
            entity.setContentType(  "application/json"  ); //設置為 json數據
            
            post.setEntity(entity);
            
            HttpResponse response = client.execute(post);
            
            HttpEntity resEntity = response.getEntity();
            String res = EntityUtils. toString(resEntity);
            
            System.  out  .println(res);
      }

問題2 Webproject怎樣去接收一個無參數的post呢?

     既然能發送,那么得想辦法實現服務端啊,要不然怎么才干死心。

     so
     測試代碼:(注,使用公司內部框架實現。但基本原理是一樣的)
     
@Path  ( "testPost"  )
  public  ActionResult getpost()  throws  Exception{
            StringBuilder sb =  new  StringBuilder ();
            InputStream is =  getRequest().getInputStream();
            BufferedInputStream bis =  new  BufferedInputStream(is);
              byte  [] buffer =  new   byte [1024];
              int  read = 0;
              while  ((read=bis.read(buffer)) != -1){
                  sb.append(  new  String(buffer, 0, read,  "UTF-8"  ));
            }
            
            System.  out  .println(sb.toString());
              return  outputStream( "{msg:success}"  );
}

    原理非常easy。直接獲取到post過來的全部數據流


上面兩個結合起來一起測試的話,結果例如以下:
     第一段代碼返回結果:
          
{msg:success}
     第二段代碼返回結果:
{"email":"dutycode@gmail.com","website":"http://www.dutycode.com"}


版權全部:《攀爬蝸牛》 => 《httpclient發送無參數的post數據
本文地址:http://www.dutycode.com/post-76.html
除非注明。文章均為 《蝸牛爬》 原版的,歡迎轉載!地址轉載本文,請注明,謝謝

版權聲明:本文博客原創文章,博客,未經同意,不得轉載。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM