Sonatype Nexus Rest API 401未经授权

时间:2013-11-07 15:47:47

标签: rest repository nexus sonatype

我正在尝试使用Rest API从java的安全nexus存储库中获取工件。我作为回应获得401 Unauthorized。

为了授权自己,我需要做些什么?

String url = "http://myNexus.com/service/local/artifact/maven/redirect?r=my-repo&g=my.group&a=my-artifact&v=LATEST";

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);

HttpResponse response = null;

response = client.execute(request);

System.out.println("Response Code : "
       + response.getStatusLine().getStatusCode());

2 个答案:

答案 0 :(得分:0)

我建议使用Nexus客户端库,而不是为REST API编写自己的Java包装器。更多详细信息和示例链接是in the Nexus book.

答案 1 :(得分:0)

我用java来模拟GET方法。第3个参数“auth”是基本的http认证示例 http://en.wikipedia.org/wiki/Basic_access_authentication
http://en.wikipedia.org/wiki/BASE64

    public String sendGet(String url, String param, String auth) {
    String result = "";
    BufferedReader in = null;
    try {
        String urlName = url + "?" + param;
        URL realUrl = new URL(urlName);
        URLConnection conn = realUrl.openConnection();
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("Accept", "application/json");
        conn.addRequestProperty("Authorization", "Basic " + auth);
        conn.connect();
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}