为HttpURLConnection添加标题

我试图添加标头为我的请求使用HttpUrlConnection但方法setRequestProperty()似乎不工作。 服务器端不会收到我的头的任何请求。

 HttpURLConnection hc; try { String authorization = ""; URL address = new URL(url); hc = (HttpURLConnection) address.openConnection(); hc.setDoOutput(true); hc.setDoInput(true); hc.setUseCaches(false); if (username != null && password != null) { authorization = username + ":" + password; } if (authorization != null) { byte[] encodedBytes; encodedBytes = Base64.encode(authorization.getBytes(), 0); authorization = "Basic " + encodedBytes; hc.setRequestProperty("Authorization", authorization); } 

在过去,我使用了以下代码,并且已经在TomCat中启用了基本身份validation:

 URL myURL = new URL(serviceURL); HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); String userCredentials = "username:password"; String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes())); myURLConnection.setRequestProperty ("Authorization", basicAuth); myURLConnection.setRequestMethod("POST"); myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length); myURLConnection.setRequestProperty("Content-Language", "en-US"); myURLConnection.setUseCaches(false); myURLConnection.setDoInput(true); myURLConnection.setDoOutput(true); 

你可以试试上面的代码。 上面的代码是用于POST的,你可以修改它为GET

只是因为我没有看到上面的答案中的这一点的信息,原始的代码片段张贴原因不能正常工作是因为encodedBytesvariables是一个byte[]而不是一个String值。 如果您将byte[]传递给一个new String() ,则代码片段完美地工作。

 encodedBytes = Base64.encode(authorization.getBytes(), 0); authorization = "Basic " + new String(encodedBytes); 

你的代码是好的。你也可以用这种方式使用相同的东西。

 public static String getResponseFromJsonURL(String url) { String jsonResponse = null; if (CommonUtility.isNotEmpty(url)) { try { /************** For getting response from HTTP URL start ***************/ URL object = new URL(url); HttpURLConnection connection = (HttpURLConnection) object .openConnection(); // int timeOut = connection.getReadTimeout(); connection.setReadTimeout(60 * 1000); connection.setConnectTimeout(60 * 1000); String authorization="xyz:xyz$123"; String encodedAuth="Basic "+Base64.encode(authorization.getBytes()); connection.setRequestProperty("Authorization", encodedAuth); int responseCode = connection.getResponseCode(); //String responseMsg = connection.getResponseMessage(); if (responseCode == 200) { InputStream inputStr = connection.getInputStream(); String encoding = connection.getContentEncoding() == null ? "UTF-8" : connection.getContentEncoding(); jsonResponse = IOUtils.toString(inputStr, encoding); /************** For getting response from HTTP URL end ***************/ } } catch (Exception e) { e.printStackTrace(); } } return jsonResponse; } 

如果授权成功,则返回响应码200

最后这为我工作

 private String buildBasicAuthorizationString(String username, String password) { String credentials = username + ":" + password; return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.DEFAULT)); } 

如果您使用的是Java 8,请使用下面的代码。

 URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8)); httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth); 

使用RestAssurd,您还可以执行以下操作:

 String path = baseApiUrl; //This is the base url of the API tested URL url = new URL(path); given(). //Rest Assured syntax contentType("application/json"). //API content type given().header("headerName", "headerValue"). //Some API contains headers to run with the API when(). get(url). then(). statusCode(200); //Assert that the response is 200 - OK