【问题标题】:Java Jersey-client header issueJava Jersey 客户端标头问题
【发布时间】:2016-10-12 10:30:04
【问题描述】:

我正在尝试将以下标头添加到 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();
            }
        }
    }

完整的香草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;
    }

【问题讨论】:

  • 错误信息是什么?可以发在这里吗?
  • @Nurzhan 错误是来自服务器的响应:{"errorCode":"21327","info":"Invalid Request"}
  • 在执行body.add 时,您不应该在密钥中包含=。它将为您添加
  • @peeskillet 做到了!!!现在工作正常,请将其添加为答案,以便我接受...

标签: java jersey


【解决方案1】:

在执行body.add 时,您不应该在密钥中包含=。会为你添加的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2015-12-03
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    相关资源
    最近更新 更多