1

我正在使用以下代码发送 REST 请求,请求失败(401 错误),因为它需要用户名和密码。

如何将它们添加到网址?即使我在浏览器中复制 url 并将用户名和密码添加到它的末尾,浏览器也会弹出登录页面,所以我想在代码中我应该添加用户名和密码参数但是如何?

  URL url = new URL("www.example.com/user?ID=1234");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
                if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

我在代码中添加了以下内容,但仍然遇到 401 错误。

             conn.setRequestProperty("username", "myusername");
             conn.setRequestProperty("password", "mypassword");
4

1 回答 1

1

尝试这个:

String params="username=myusername&password=mypassword";
conn.getOutputStream().write(params.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();

或者您可能需要对参数进行编码:

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

String postContent = URLEncoder.encode("username", "UTF-8") + "=" + 
                     URLEncoder.encode(myusername, "UTF-8") + "&" + 
                     URLEncoder.encode("password", "UTF-8") + "=" + 
                     URLEncoder.encode(mypassword, "UTF-8") ;

dos.write(postContent.getBytes());
dos.flush();
dos.close();

关于基本授权

String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
uc.connect();
于 2013-03-22T04:31:27.843 回答