【发布时间】:2016-01-16 10:06:59
【问题描述】:
我正在使用javax.servlet.http.HttpServlet 创建和初始化我的服务器。
我正在 IBM WebSphere Liberty 服务器上部署我的 servlet。
当我尝试进行任何 REST 调用时,我收到 401 Unauthorized 错误。
HttpURLConnection conn = null;
String url = "https://someurl/getdata";
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
String accessToken = this.token;
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
conn.setRequestProperty("Accept", "application/json;charset=utf-8");
conn.setRequestProperty("X-Auth-Token", "bmXaj83sgo4"); } catch (Exception e) {
e.printStackTrace();
}
在该行抛出NullPointerException 或返回401 Unouthorized 错误:
conn = (HttpURLConnection) url.openConnection();
但我可以通过 RestClient 或使用简单的 Java 项目访问相同的 URL。
我的web.xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>SampleTesting</display-name>
<servlet>
<servlet-name>Monkey Server</servlet-name>
<servlet-class>com.sample.testing.basic.BasicMonkeyServer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
【问题讨论】:
-
问题中的代码不会编译给定的 url 是字符串而不是 java.net.URL。如果您提供了实际代码和异常,它可能会有所帮助。获得 401 时,您是否检查过您是否可以访问?访问的资源是否受到保护,您是否提供了任何凭据?
-
@Alasdair:谢谢你的回复。是的,你是对的。我正在将 URL 从字符串类型转换为 java.net.URL。
标签: servlets jax-rs httpurlconnection httpserver websphere-liberty