【问题标题】:Accessing JSON in using JSESSION ID or Authentication使用 JSESSION ID 或 Authentication 访问 JSON
【发布时间】:2023-04-10 01:24:02
【问题描述】:

我在 Eclipse 中创建了一个简单的 Java 项目(不是动态 Web 项目)。

我希望能够访问返回一些 JSON 值的 Web URL。

我可以使用 HttpClient 和所有其他方法访问 URL,但我无法验证我的会话,这是我访问 JSON 数据所必需的。如果您未通过身份验证,该 URL 会将您重定向到登录页面。

我尝试了多种验证会话的方法,但似乎都不起作用——我总是得到登录页面的 HTML 数据而不是 JSON。

我还注意到 JSESSION ID 被传递到请求标头中,但我似乎无法弄清楚如何创建 JSESSION ID 以及如何将其传递到 GET 请求中。

所以基本上,我可以通过两种方式解决这个问题:

  1. 验证我的会话,然后访问 URL 以获取 JSON
  2. 创建一个 JSESSION ID 并将其传递到 GET 请求中以获取 JSON

有人知道怎么做吗?

最后,我想使用从 JSON 收集的数据进行一些 Selenium 测试,所以我需要在动态 Web 项目(在 Eclipse 中)中完成所有这些工作,还是可以在常规 Java 中完成所有这些工作项目?


尝试 1

URL url = new URL(_url);

InputStream ins = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
StringBuilder builder = new StringBuilder();

for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
}

System.out.println("RESPONSE:\n\n" + builder);

JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

System.out.println("JSON:\n\n" + finalResult.toString());

尝试 1 次结果

我最终打印出登录页面的 HTML 代码,然后收到以下错误消息,因为页面上没有 JSON:

Exception in thread "main" org.json.JSONException: A JSONArray text must start with '[' at character 1

尝试 2

我也试过Oracle's Http Authentication页面中的代码:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

public class RunHttpSpnego {

    static final String kuser = "username"; // your account name
    static final String kpass = "password"; // your password for the account

    static class MyAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            // I haven't checked getRequestingScheme() here, since for NTLM
            // and Negotiate, the usrname and password are all the same.
            System.err.println("Feeding username and password for " + getRequestingScheme());
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new MyAuthenticator());
        URL url = new URL(args[0]);
        InputStream ins = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        String str;
        while((str = reader.readLine()) != null)
            System.out.println(str);
    }
}

【问题讨论】:

    标签: java json authentication apache-httpclient-4.x jsessionid


    【解决方案1】:

    当您登录时,服务器会在您的浏览器中使用响应中的 Set-Cookie 标头将会话 ID 设置为 cookie。

    Set-Cookie: name=value
    Set-Cookie: name2=value2; Expires=Wed, 09-Jun-2021 10:18:14 GMT
    

    然后,浏览器在请求标头中随每个后续请求向服务器提供此 cookie。

    Cookie: name=value; name2=value2
    

    HttpClient 可以为你做这个管理,就像浏览器一样。见http://hc.apache.org/httpclient-3.x/cookies.html 因此,您首先要告诉 HttpClient 浏览登录页面,它会获取您的 cookie,并在随后的请求中将其发送。

    您也可以自行处理并手动设置 cookie。在 HttpClient 3 中,这看起来像这样:

    HttpMethod method = new GetMethod();
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Cookie", "special-cookie=value");
    

    如何在 HttpClient 4 中设置 cookie 可以在这里找到:Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request

    或者您可以将其降低一点并添加完整的标题。

    HttpGet httpget = new HttpGet(url); 
    httpget.addHeader("Cookie", "JSESSIONID=...");
    

    【讨论】:

    • 所以我可以做类似method.setRequestHeader("Cookie", "JSESSIONID=F7B89109EABD2FFD58A0096AF2123199"); 的事情,它应该可以工作吗?
    • 我该如何使用HttpMethodGetMethod?我已经添加了从您链接到的 Apache 网站下载的 JAR 文件,但现在确定要调用什么 import
    • 哎呀,我现在知道您要求使用 HttpClient 4。我使用的名称是用于 HttpClient 3。并不是说它有那么大的区别。
    • 对于 HttpClient 4 手动设置 cookie 看起来像这样stackoverflow.com/questions/4166129/…
    • 我已将其添加到答案中
    猜你喜欢
    • 2012-08-10
    • 2017-12-22
    • 2022-12-09
    • 2021-10-17
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多