Eclipse Kura http authentication failed

77 Views Asked by At

I am trying to do a simple HTTP Get and POST request in java to my Eclipse Kura gateway but i dont know how to authenticate using username and password. I tried using the url syntax http://user:pw@ipaddress:port/ but i still get HTTP error code 401.

import java.io.*;
import java.net.*;

public class HTTP {

public static String getHTML() throws Exception {
    StringBuilder result = new StringBuilder();

    String urlToRead = "http://user:pw@ipaddress:port";

    URL url = new URL(urlToRead);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    rd.close();
    return result.toString();
}

public static void main(String[] args) throws Exception {
    System.out.println(getHTML());
}
}
1

There are 1 best solutions below

0
On

I believe that you are not providing the credentials in the desired way. This very similar question already has an accepted answer, in which James Van Huis suggests using java.net.Authenticator for setting authentication data prior to opening any connections.