此代码用于从某些URL获取文本,该URL具有指定的below.Tried的自定义身份验证,甚至使用ajax和Jquery作为dataType:"jsonp“,但它也显示了401 error。
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();
}
当试图对具有自定义身份验证的url进行身份验证时,如代码所示,它将返回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
发布于 2014-05-30 23:00:44
实际上,这里的问题是您传递的授权属性没有编码。
您需要将其传递给Base64编码器,以便http授权机制能够使用它。
当需要在网络上存储和传输二进制数据时,通常使用Base64编码。
将编码添加到代码中。将代码更改为:
你需要用
Base64.encodeToString()
执行编码。
以下链接将对您提供更多帮助:http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java
https://stackoverflow.com/questions/23881452
复制相似问题