I'm trying to get an artifact from a secured nexus repository from java using the Rest API. I'm getting 401 Unauthorized as a response.
What do I need to do in order to authorize myself?
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());
I would suggest to use the Nexus Client library rather than writing your own Java wrapper for the REST API. More details and links to examples are in the Nexus book.
I used java to simulate GET method. The 3rd param "auth" is the basic http authentication example.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.