httpclient raw請求


最近開發中需要從一個第三方系統中獲取數據,使用到了httpclient方法:

httpclient raw請求:

    /**
     * java發送raw
     * @url 請求地址
     * @param 請求參數
     * @return 返回響應內容
     */
public static String rawPost(String url,String param) {

        //HttpClients.createDefault()等價於 HttpClientBuilder.create().build();   
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();   
        HttpPost httpost = new HttpPost(url);  
        //JSONObject jsonString = JSON.parseObject(param);
        //設置header
        httpost.setHeader("Content-type", "application/json");    
        httpost.addHeader("appid", "502");
        httpost.addHeader("username", "menhu");
        //組織請求參數  
        StringEntity stringEntity = new StringEntity(param);  
        httpost.setEntity(stringEntity);  
        String content = null;  
        CloseableHttpResponse  httpResponse = null;  
        try {  
            //響應信息
            httpResponse = closeableHttpClient.execute(httpost);  
            HttpEntity entity = httpResponse.getEntity();  
            content = EntityUtils.toString(entity);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                httpResponse.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        try {  //關閉連接、釋放資源  
            closeableHttpClient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }    
        return content; 
    }

客戶端獲取請求的參數

注意事項:獲取請求參數時使用request.getParameter無法獲取參數,需要使用流的方式來獲取具體的請求參數:

 


免責聲明!

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



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