gpt4 book ai didi

Java OkHttp请求无法满足

转载 作者:行者123 更新时间:2023-12-02 02:33:32 25 4
gpt4 key购买 nike

我正在使用 okhttp 从 URL 下载字符串。这是代码。

public static void main(String[] args) throws InterruptedException {
String jsonString = downloadJsonString("https://api.korbit.co.kr/v1/ticker/detailed?currency_pair=btc_krw");
System.out.println(jsonString);
}

String downloadJsonString (String url) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}

结果是这样的:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Request blocked.
<BR clear="all">
<HR noshade size="1px">
<PRE>Generated by cloudfront (CloudFront)
Request ID: jIs6PvNF01BMsQrynj4pk8eBXuQW-n-Q02Tav0SQghSZ7TzZOFfrAg==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>

如果我将网址输入浏览器,它就可以正常工作。以下是回复:

{"timestamp":1507942765556,"last":"6355000","bid":"6355000","ask":"6358500","low":"6310000","high":"6949000","volume":"12329.815314799943534093","change":"0","changePercent":"0"}

如何解决?

最佳答案

您收到的响应是 Korbit 的 403 Forbidden 响应。您收到此响应是因为 Korbit API 要求您提供一些身份验证详细信息。来自 the docs :

Prior to using Korbit API, you need to authenticate a user. As Korbit API provides OAuth 2.0 interface, you get an access token after a successful authentication. For each API request, you need to set Authorization HTTP header with the access token. API Keys and Secrets

You need to request an API key and secret to use Korbit API. All Korbit users can get the API key through the Korbit website. You can sign in into your Korbit account by direct authentication API call, which requires username and password in the body of the POST request to get an access token (and a refresh token). In this document, denotes an API key, and denotes a corresponding API secret.

因此,您向 Korbit 注册,他们为您提供一些身份验证详细信息,然后您将这些详细信息包含在 HTTP 请求中。

您表示相同调用是通过您的浏览器完成的,这一定是因为 Korbit 允许源自浏览器(而不是编程式 HTTP 客户端)的未经身份验证的调用。为了证明这一点,只需跟踪浏览器中的调用,您会发现该请求包含一个名为“User-Agent”的 header ,其中 one of these values .

可以在代码中模仿这一点,如下所示:

Request request = new Request.Builder()
.url(url)
.header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0)")
.build();

这将使您的调用成功完成,但不建议这样做,我怀疑 Korbit 在有限次数的尝试后会禁止它。相反,您需要遵循 Korbit's instructions并注册您自己,然后在请求 header 中提供您的身份验证详细信息。

关于Java OkHttp请求无法满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com