Java 發送HTTP-POST請求


`

      // 發送請求HTTP-POST請求 url:請求地址; entity:json格式請求參數
      public static String post(String url, String entity) {
	try {
              String username="user";// 賬戶
              String password="1234";// 密碼		      
              CloseableHttpClient httpClient = HttpClients.createDefault();
              HttpPost httpPost = new HttpPost(url);
              httpPost.addHeader("Authorization", "Basic " + java.util.Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
              StringEntity se = new StringEntity(entity, "UTF-8");
              se.setContentType("application/json");
              httpPost.setEntity(se);
              CloseableHttpResponse response = httpClient.execute(httpPost);
              HttpEntity entity1 = response.getEntity();
              String resStr = null;
              if (entity1 != null) {
                  resStr = EntityUtils.toString(entity1, "UTF-8");
              }
              httpClient.close();
              response.close();
              return resStr;
	  } catch (Exception e) {
              e.printStackTrace();
	  }
	  return "";
      }

`


免責聲明!

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



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