我想连接“ https://api.tdax.com/api/orders/?pair=btc_thb” 这个网址适用于chrome,邮递员。 我可以将此网址与C#连接。 但是不能与Java连接。
namespace Exchanges.Satang
{
class SatangApi
{
private static class WebApi
{
private static readonly HttpClient st_client = new HttpClient();
static WebApi()
{
st_client.Timeout = TimeSpan.FromSeconds(2);
}
public static HttpClient Client { get { return st_client; } }
public static string Query(string url)
{
var resultString = Client.GetStringAsync(url).Result;
return resultString;
}
}
public static string GetOrders(string symbol)
{
const string queryStr = "https://api.tdax.com/api/orders/?pair=";
var response = WebApi.Query(queryStr + symbol);
return response.ToString();
}
}
}
此C#代码运行良好 但是遵循以下Java代码无法正常工作,则会显示403错误。
private String publicOperation(String operation) throws IOException, BadResponseException {
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
答案 0 :(得分:4)
某些服务器希望在请求中包含User-Agent
头,以将其视为有效请求。因此,您需要按如下所示将其添加到您的请求中。
con.setRequestProperty("User-Agent", "My-User-Agent");
int responseCode = con.getResponseCode();
此标头的值(在上例中为My-User-Agent
)可以设置为此端点所需的任何String。例如,邮递员为此设置了PostmanRuntime/7.16.3
之类的东西。
C#可能在内部执行此操作,因此您不必显式设置它。
答案 1 :(得分:0)
public String getOrders(SatangCurrencyPairs currencyPair) throws IOException, BadResponseException {
String operation="orders/?pair="+currencyPair.toString();
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
//URL url_ = new URL("https://api.tdax.com/api/orders/?pair=btc_thb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "java client");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}