httpclient之發送字符串


public String HttpPostWithJson(String url, String json) {
        String returnValue = "這是默認返回值,接口調用失敗";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步:創建HttpClient對象
         httpClient = HttpClients.createDefault();
             
             //第二步:創建httpPost對象
            HttpPost httpPost = new HttpPost(url);
            
            //第三步:給httpPost設置JSON格式的參數
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");                
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
           
           //第四步:發送HttpPost請求,獲取返回值
           returnValue = httpClient.execute(httpPost,responseHandler); //調接口獲取返回值時,必須用此方法
//           CloseableHttpResponse httpResonse = httpClient.execute(httpPost);
//           int statusCode = httpResonse.getStatusLine().getStatusCode();
//           if(statusCode!=200)
//           {
//                System.out.println("請求發送失敗,失敗的返回參數為:"+httpResonse.getStatusLine());
//                returnValue = httpResonse.getStatusLine().toString();      
//           }
//           
          
        }
         catch(Exception e)
        {
             e.printStackTrace();
        }
        
        finally {
           try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
         //第五步:處理返回值
         return returnValue;
    }

 


免責聲明!

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



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