Java Jersey 客户端 header 问题

标签 java jersey

我正在尝试将以下 header 添加到 rest Post 调用中...它可以在纯 Java 中运行,但我正在尝试使用 Jersey 客户端库重新编写它...当我使用 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;
    }

最佳答案

你不应该有 =在做 body.add 时的关键.将为您添加

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

关于Java Jersey 客户端 header 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39996366/

相关文章:

java - Android:通过存储在应用程序类中避免将 Activity 传递给单例=内存泄漏?

java - 无法理解 Spring Boot 如何使用 maven 管理集成测试。它是否使用故障安全插件?

java - .classpath 中排除了 Spring Boot + Eclipse : why application. 属性?

java - 在没有 main() 方法的情况下,所有注释如何在 TestNg 中工作

java - 新泽西州在提交帖子时无法添加参数

java - 如何在 REST API 中表达查询参数之间的高级表达式?

Jersey 2.0-m2 中的 JSON 支持

java - 使用JScience解析mathml文档

java - 可以在构建时生成wadl文件吗?

javascript - JSON Javascript 不起作用?