java post 發送請求並獲取返回值

java post 發送數據並且拿到服務器返回的參數

最近用了很多post發送數據,就想着把這個記錄一下
廢話不多說,這個是發送數據的。

    /**post 發送作業數據*/
    public static  void doPost(String data,String url) {
        //創建httpclient對象
        try{
            CloseableHttpClient client = HttpClients.createDefault();
            //創建post方式請求對象
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("imageBase64",data));
            //url格式編碼
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
            httpPost.setEntity(uefEntity);
            CloseableHttpResponse response = client.execute(httpPost);
            // 檢驗返回碼
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != 200){
                httpPost.abort();
                httpPost.releaseConnection();
            }else {
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                String string = changeInputStream(stream, "utf-8");
                System.out.println(string + "-----------");
            }
            httpPost.releaseConnection();
        }catch (IOException io){
            io.printStackTrace();
            System.out.println(io + "send homeworkJson error");
        }
    }
  

這個是接收返回參數的

// 將輸入流按照編碼格式讀取爲字符
  private static String changeInputStream(InputStream inputStream,  String encode) {
      
      //創建字節流
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      byte[] data = new byte[1024];
      int len = 0;
      String result=null;
      if (inputStream != null) {
          try {
              while ((len = inputStream.read(data)) != -1) {
                  outputStream.write(data, 0, len);
              }
              //將字節轉換爲字符串
              result = new String(outputStream.toByteArray(), encode);
          } catch (IOException e) {
              e.printStackTrace();
          }

      }
      return result;
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章