【问题标题】:A JSONObject text must begin with '{' at 1 [character 2 line 1], getting this error while automating API using HTTPClientJSONObject 文本必须在 1 [character 2 line 1] 处以 '{' 开头,在使用 HTTPClient 自动化 API 时出现此错误
【发布时间】:2021-04-24 12:45:40
【问题描述】:

我正在使用 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” }

【问题讨论】:

    标签: java json jackson httpclient


    【解决方案1】:

    万岁,我自己找到了解决这个问题的方法,现在可以正常工作了

    我们需要在 header 中传递一个 cookie,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多