使用get请求在redmain中失败HTTP

时间:2015-10-21 20:45:31

标签: java authentication

我在vmware机器上启动了bitnami的iso。 bitnami的标准管理登录和传递是: 登录:用户, 传:bitnami。

在Authentication选项卡中选择Authentication required,启用REST Web服务并启用JSONP支持。

任何人都知道,为什么我得到以下陈述? 如有任何帮助,我将非常感激。

我收到了一份声明:

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP
error code : 401 at NetClientGet.main(NetClientGet.java:36)
Java Result: 1

我的代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientGet {

    public static void main(String[] args) {

      try {
        URL url = new URL("http://192.168.0.78/issues.json?key=pjxjDvD9ez0Qm97iApka");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setDoOutput(true);

        if (conn.getResponseCode() != 200) {
          throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
          System.out.println(output);
        }
        conn.disconnect();

      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
}

1 个答案:

答案 0 :(得分:0)

HTTP状态代码401表示您遇到身份验证问题。这与你的代码无关。

但是,对于错误的状态代码抛出RuntimeException是很糟糕的。

if (conn.getResponseCode() != 200) {
  throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}

也许你可以优雅地处理不同的场景。示例:

if (conn.getResponseCode() >= 300) {
  // Something unexpected happened
  System.out.println("Unexpected response from server");
  return // Stop here
}

修改

抱歉,我没有仔细阅读您的密码。根据您获得的状态代码,您似乎需要向服务器发送HTTP身份验证。它看起来像那样:

String username = "user"
String password = "bitnami"
String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());

URL url = new URL("http://192.168.0.78/issues.json?key=pjxjDvD9ez0Qm97iApka");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

注意:不承诺它将编译/工作:)

从此SO主题获取的代码:"How to handle HTTP authentication using HttpURLConnection?"