如何为restful请求添加参数?

时间:2013-03-22 04:25:00

标签: java rest java-ee restful-url

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

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

  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");

1 个答案:

答案 0 :(得分:1)

试试这个:

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

或许你需要编码params:

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();

关于Basic Authorization

String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
uc.connect();