Java Jersey-client头问题

时间:2016-10-12 10:30:04

标签: java jersey

我试图将以下标题添加到休息后调用...它在普通Java中工作但我尝试使用Jersey客户端库重新编写它...当我制作时泽西岛的帖子我得到的错误代码没有在API文档中列出,所以我知道它必须只是一个小问题,比如缺少标题......任何想法我在底部做错了什么功能

普通Java添加标头功能:

private void SetDefaultHeaders(HttpURLConnection conn) {
        setRequestProperty(conn, "Accept", "*");
        setRequestProperty(conn, "Content-Type", "application/x-www-form-urlencoded");
}

泽西岛代码:

public void logIn(String email, String password) {
        if (email != "" && email != null && password != "" && password != null) {
            try {
                StringBuilder sb = new StringBuilder();
                sb.append(Settings.WIFIPLUG_URL);
                sb.append("/user_login");

MultivaluedMap<String, String> body = new MultivaluedMapImpl();
                body.add("username=", email);
                body.add("password=", password);    

                System.out.println("login url: " + sb.toString());

                WebResource webResource = Client.create(new DefaultClientConfig()).resource(sb.toString());

                WebResource.Builder builder = webResource.accept("*");
                builder.type("application/x-www-form-urlencoded");

                ClientResponse response = builder.post(ClientResponse.class, body);

                if (response.getStatus() != 200) {
                    throw new RuntimeException("failed: http error code " + response.getStatus());
                }
                System.out.println("Response from server: " + response.getEntity(String.class));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

完整的vanilla java登录功能:

public String postUserLogin(String username, String password) {
        String result = "";
        // URL for API to login
        String url = "https://wifiplugapi.co.uk:3081/zcloud/api/user_login";
        String requestParams = "username=" + username + "&password=" + password;

        try {
            URL obj = new URL(url);
            System.out.println("login url: " + obj);

            // Opens the connection
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

            // Send POST request
            con.setDoOutput(true);
            con.setDoInput(true);

            // Request Headers
            con.setRequestMethod("POST");

            // Sets all the headers
            SetDefaultHeaders(con);

            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            wr.write(requestParams);// adds values to the request
            wr.flush();
            wr.close();

            // Handles the response
            StringBuilder sb = new StringBuilder();
            int responseCode = con.getResponseCode();
            if (responseCode == 200) {
                // if the request was successful OK = 200
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                // Returns Token
            } else {
                // If the request was bad, reason will be printed
                result = "Error, login request failed";
                throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
            }

            result = sb.toString();

            // JSON Parser
            JsonParser parser = new JsonParser();

            JsonObject resultObj = parser.parse(result).getAsJsonObject();
            con.disconnect();

            if (resultObj.get("token") != null) {
                result = (resultObj.get("token")).toString();
                System.out.println("JSONObject Result (token): " + result);
            } else {
                System.out.println("result = " + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // returns token value in string ie. fdg573gb3789gv923378gy83g3
        result = result.replaceAll("\"", "");
        return result;
    }

1 个答案:

答案 0 :(得分:1)

在执行=时,您不应该在密钥中拥有body.add。它将为您添加

MultivaluedMap<String, String> body = new MultivaluedMapImpl();
body.add("username=", email);     // remove the =
body.add("password=", password);  // remove the =