【问题标题】:Restful URL custom authentication failing in javajava中的Restful URL自定义身份验证失败
【发布时间】:2014-07-15 21:30:13
【问题描述】:

此代码用于从具有自定义身份验证的某个 URL 获取文本,如下所示。尝试使用 ajaxJquery 作为 dataType:"jsonp" 但它也显示 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();
  }

当尝试对具有某些自定义身份验证的 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

【问题讨论】:

    标签: rest restful-authentication restful-url


    【解决方案1】:

    这里的问题实际上是你传递的授权属性没有编码。

    您需要将其传递给 Base64 编码器,以便 http 授权机制将使用它。

    当需要对通过网络存储和传输的二进制数据进行编码/解码时,通常使用

    Base64 编码

    为您的代码添加编码。将您的代码更改为:

    你需要使用

    Base64.encodeToString()

    执行编码。

    以下链接将为您提供更多帮助: http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 2016-03-15
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      相关资源
      最近更新 更多