HttpClient 调用远程服务,POST 请求 ,x-csrf-token验证失败,报CSRF token validation failed 问题解决

首先通过 HttpGet 来获取x-csrf-token,代码如下:

HttpGet httpget = new HttpGet(url);
httpget.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpget.setHeader("Authorization", code);
httpget.setHeader("x-csrf-token", "fetch");
Header headers[] = httpget.getAllHeaders();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse res = httpclient.execute(httpget);

遍历headers,得到 cookies和x-csrf-token值

headers = res.getAllHeaders();
for (Header h : headers) {
   if (h.getName().equals("set-cookie")) {
      Token = Token+h.getValue()+";";
   }
   if (h.getName().equals("x-csrf-token")) {
      Token = Token+";"+h.getValue();
   }
}

post调用方法如下:

HttpClient client = new DefaultHttpClient();
      HttpPost post = new HttpPost(url);

      
      post.addHeader("Content-Type", "application/json");
      post.addHeader("Authorization", "******");    //用户密码验证的
      post.setHeader("X-CSRF-Token", Token.split(";;")[1]);
      post.setHeader("cookie", Token.split(";;")[0]);
      String result = "";

      try {
         StringEntity s = new StringEntity(json, "utf8");
         s.setContentType(new BasicHeader("Content-Type",
               "application/json"));
         post.setEntity(s);
         // 发送请求
         HttpResponse httpResponse = client.execute(post);

         // 获取响应输入流
         InputStream inStream = httpResponse.getEntity().getContent();
         BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
         StringBuilder strber = new StringBuilder();
         String line = null;
         while ((line = reader.readLine()) != null)
            strber.append(line + "\n");
         inStream.close();
         result = strber.toString();
         if (httpResponse.getStatusLine().getStatusCode() == 201) {
            System.out.println("请求服务器成功,做相应处理");
         } else {
            System.out.println("请求服务端失败");
         }
      } catch (Exception e) {
         System.out.println("请求异常");
         throw new RuntimeException(e);
      }
      return result;
最开始的时候 post 并没有去header设置cookie,所以一直报CSRF token validation failed。把 cookie 设置上后就可以了
阅读更多
文章标签: x-csrf-token
个人分类: java x-csrf-token
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭