此代码用于从具有下面指定的自定义身份验证的某个网址获取文本。甚至包含 ajax 和 Jquery 作为dataType:" jsonp& #34;但它也显示 401错误。
URL u;
HttpURLConnection con;
InputStream is = null;
DataInputStream dis;
String s;
try {
// u = new URL("http://q.addthis.com/feeds/1.0/trending.json?pubid=atblog");
u = new URL("http://m2mportal.connectm.com/EMS/rest/device");
is = u.openStream();
con=(HttpURLConnection) u.openConnection();
con.connect();
con.setDoOutput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Accept","application/json");
con.setRequestProperty("Authorization","authenticate\":{\"userName\":\"admin01\",\"password\":\"admin01$\",\"appId\":\"123\"}");
con.setRequestProperty("userName","admin01");
con.setRequestProperty("password","admin01$");
con.setRequestProperty("appId","123");
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null)
{
System.out.println(s);
}
}
catch (MalformedURLException mue)
{
System.out.println("Ouch - a MalformedURLException happened.");
mue.printStackTrace();
System.exit(1);
}
catch (IOException ioe)
{
System.out.println("Oops- an IOException happened.");
ioe.printStackTrace();
System.exit(1);
}
catch(IllegalStateException ise)
{
System.out.println("In IllegalState Exception........");
ise.printStackTrace();
}
当尝试对具有某些自定义身份验证的网址进行身份验证时,如代码所示,它返回 401错误
Oops- an IOException happened.
java.io.IOException: Server returned HTTP response code: 401 for URL: some url
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at java.net.URL.openStream(URL.java:1037)
at com.techm.JavaGetUrl.main(JavaGetUrl.java:16)
Java Result: 1
答案 0 :(得分:0)
这里的问题实际上是您传递的Authorization属性未编码。
您需要将其传递给Base64编码器,以便http授权机制将使用它。
当需要对通过网络存储和传输的二进制数据进行编码/解码时,通常会使用Base64编码。
为您的代码添加编码。将您的代码更改为:
你需要使用
Base64.encodeToString()
执行编码。
以下链接可以为您提供更多帮助: http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java