基於http的restFul請求


1.Java 用HTTP的方式發送JSON報文請求

  public String sendPOSTJsonRequest(String path,String query){

     String resp= "";
      HttpURLConnection connection =null;
        try {
         //定義請求地址
            URL url = new URL(path); //url地址
            //打開鏈接
            connection = (HttpURLConnection) url.openConnection();
            //doInput默認為true,說明可以從服務器獲取數據
          //設置是否從httpUrlConnection讀入,默認情況下是true;
            connection.setDoInput(true);
            //doOutput默認為false,含義程序不可以從URL拿數據,所有post請求要設置為true
            //設置是否向httpUrlConnection輸出,因為這個是post請求,參數要放在
            //http正文內,因此需要設為true, 默認情況下是false;
            connection.setDoOutput(true);
            //請求方式
            connection.setRequestMethod("POST");
            //Post 請求不能使用緩存
            connection.setUseCaches(false);
            //要在HttpURLConnection實例化之前設置HttpURLConnection.setFollowRedirects(false)。
            //setFollowRedirects()是靜態方法,設置為false后后面實例化的HttpURLConnection對象
            //才不會發生重定向,如果在setFollowRedirects()設置為false之前就得到HttpURLConnection對象,
            //則該對象的setFollowRedirects()為默認的true。看來setFollowRedircts()的順序很重要。
            connection.setInstanceFollowRedirects(true);
            //獲取 request 中用POST方式"Content-type"是"application/json"發送的 json 數據
            connection.setRequestProperty("Content-Type","application/json");
            //鏈接
            connection.connect();
           
            //post參數的方法
            //此處getOutputStream會隱含的進行connect(即:如同調用上面的connect()方法,
            try (OutputStream os = connection.getOutputStream()) {
             //向對象輸出流寫出數據,這些數據將存到內存緩沖區中
                os.write(query.getBytes("UTF-8"));
            }
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                String lines;
                StringBuffer sbf = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sbf.append(lines);
                }
                resp = sbf.toString();   
              
            }
           
           return resp;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
             connection.disconnect();
            }
          
        }
     return resp;
  }     
      

2.Java 用HTTP的方式發送get報文請求

   public boolean sendGETRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
            StringBuilder url = new StringBuilder(path);
            url.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                   url.append(entry.getKey()).append("=");
                   url.append(URLEncoder.encode(entry.getValue(), encoding));// 編碼
                   url.append('&');
             }
            url.deleteCharAt(url.length() - 1);
           HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
           connection.setConnectTimeout(5000);
           connection.setRequestMethod("GET");
           if (connection.getResponseCode() == 200) {
              return true;
          }
         return false;
     }

 

3.通過通過HttpClient框架發送POST請求

   /**

     * 通過HttpClient框架發送POST請求
     * HttpClient該框架已經集成在android開發包中
     * 此框架封裝了很多的工具類,性能比不上自己手寫的下面兩個方法
     * 但是該方法可以提高程序員的開發速度,降低開發難度
     */
    private static boolean sendHttpClientPOSTRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放請求參數
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                //BasicNameValuePair實現了NameValuePair接口
                pairs.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);    //pairs:請求參數   encoding:編碼方式
        HttpPost httpPost = new HttpPost(path); //path:請求路徑
        httpPost.setEntity(entity);

 

        DefaultHttpClient client = new DefaultHttpClient(); //相當於瀏覽器
        HttpResponse response = client.execute(httpPost);  //相當於執行POST請求
        //取得狀態行中的狀態碼
        if (response.getStatusLine().getStatusCode() == 200) {
            return true;
        }
        return false;
    }
 
 
4.參數以xml放入
 public static boolean sendXML(String path, String xml)throws Exception  
    {  
        byte[] data = xml.getBytes();  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setConnectTimeout(5 * 1000);  
        //如果通過post提交數據,必須設置允許對外輸出數據  
        conn.setDoOutput(true);  
         conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");  
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
        OutputStream outStream = conn.getOutputStream();  
        outStream.write(data);  
        outStream.flush();  
        outStream.close();  
        if(conn.getResponseCode()==200)  
        {  
            return true;  
        }  
        return false;  
    }  
 

 jar:

 

 

 

學習來源:https://blog.csdn.net/minzhimo4854/article/details/88925461

                  https://www.cnblogs.com/zjshd/p/9149643.html

                  https://www.cnblogs.com/wang-yaz/p/9237981.html

                  https://www.cnblogs.com/longshiyVip/p/5066285.html

                  https://www.cnblogs.com/lukelook/p/11169219.html

                  http://www.voidcn.com/article/p-xifhsqww-ys.html

                  https://blog.csdn.net/qq_26819733/article/details/52752170

                  https://vimsky.com/examples/detail/java-method-java.net.HttpURLConnection.setDefaultUseCaches.html

                  https://wenku.baidu.com/view/48f3c5d226fff705cc170ad1.html

                  https://ask.csdn.net/questions/243757

                  //獲取 request 中用POST方式"Content-type"是"application/json"發送的 json 數據

                  https://blog.csdn.net/seapeak007/article/details/70320199

                  //post 的json請求

                  https://www.cnblogs.com/wqsbk/p/6771045.html

                //jar

                https://blog.csdn.net/mhqyr422/article/details/79787518

                //前段構建請求

                https://my.oschina.net/u/3970421/blog/3055110

                //理論

                https://www.jianshu.com/p/21622d81ab26

               //JSON數據交互和RESTful支持

 

               https://blog.csdn.net/qq_37820491/article/details/89682923

                //基於不同框架的實現

               https://zhuanlan.zhihu.com/p/69285935

                https://cloud.tencent.com/developer/article/1552692

                https://blog.csdn.net/beijing20110905/article/details/17508177

                 //發送xml

                https://blog.csdn.net/Roben518/article/details/52247970


免責聲明!

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



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