有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSONObject文本必须在1[字符2第1行]处以“{”开头,在使用HTTPClient自动化API时出现此错误

我正在使用HTTPCLIENT自动化我的项目Web服务,并在获得csrf令牌后尝试登录,但我从响应中收到此错误,即使经过多次尝试,我也无法修复此错误

    restClient = new RestClient();
    HashMap<String, String> headerMaps = new HashMap<String, String>(); // Add header values
    headerMaps.put("Content-Type", "application/json");
    headerMaps.put("Connection", "keep-alive");
    headerMaps.put("csrfToken", "test12");

 // Jackson API : to convert java class object into JSON
    ObjectMapper mapper = new ObjectMapper();
    Users users = new Users("test@test.com", "abcd");

 // Object to Jsonfile :mapper.writeValue(new 
    File("C:/NewEclipse/Projectn/src/main/java/com/qa/data/users.json"),users);

//  Object to json in String:String usersJsonString = mapper.writerWithDefaultPrettyPrinter()
            .writeValueAsString(users);

    System.out.println("Users json value is----> " + usersJsonString);

    // Call the Post method
    closeableHttpResponse = restClient.postLogin(url, usersJsonString,headerMaps);

    String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");

    System.out.println("Value of RESPONSE STRING----> " + responseString);

    JSONObject responseJson = new JSONObject(responseString); //Here I am getting error mentioned in subject

我得到的JSON值也是正确的:
{ “电子邮件”:test@test.com", “密码”:“abcd” }


共 (1) 个答案

  1. # 1 楼答案

    万岁!我自己找到了解决这个问题的办法,现在效果很好

    我们需要在标题中传递cookie,如下所示:

    headerMaps.put("cookie","_csrf=value; connect.sid=value; csrfToken=value")