有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

rest RESTFUL jetty服务返回403错误java

当我试图从java代码中调用https REST服务时,我面临来自https REST服务的HTTP 403禁止响应。如果我遗漏了什么,你能告诉我吗

请注意,当我触发来自任何浏览器/SOAPUI/Chrome Postman客户端的请求时,服务器返回预期数据。 使用2个对等证书-如发送请求后soapui中的ssl信息所示

代码片段已附加。[我在代码中设置的标题取自我从成功请求中找到的请求标题]

HttpsURLConnection connection = (HttpsURLConnection)new URL("https://server address").openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
connection.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1");
connection.addRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("Cache-Control","no-cache");
connection.setRequestMethod("GET");
connection.connect();

System.out.println("Response Code : " + connection.getResponseCode()+" "+connection.getResponseMessage());

响应代码:403禁止


共 (2) 个答案

  1. # 1 楼答案

    谢谢你的回复。问题在于用于连接的会话cookie。一旦带有JSESSIONID的cookie作为头传递,我们就能够连接并获得响应代码为HTTP 200的响应。再次感谢

  2. # 2 楼答案

    请检查服务器URL是否为Java可接受的格式,好吗
    有时java需要转义字符来正确识别字符串。 这个问题:What are all the escape characters?可以帮助您检查是否使用了这些字符中的任何一个。还要检查函数中的转换是否正确完成。 另外,如果你有更复杂的URL,考虑使用java。网网址。
    最后,检查用户代理参数Setting user agent of a java URLConnection