如何在Java中的GET请求中传递用户名和密码

时间:2014-11-26 13:23:20

标签: java httpclient

以下是我编写的代码。 但是当我发送请求时,我得到了响应代码401:Unathorized。

    String url = "SAMPLE_URL";
    URL obj = new URL(url);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");
    //add request header
    //con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

1 个答案:

答案 0 :(得分:1)

obj.openConnection();

之后将此代码添加到您的计划中
String encoded = Base64.encode(username+":"+password);
con.setRequestProperty("Authorization", "Basic "+encoded);