【发布时间】:2020-03-30 15:00:41
【问题描述】:
我目前正在尝试与 Tidal API 交互,但遇到了一些麻烦。这是我的代码,我正在使用 Volley 库:
JSONObject pload = new JSONObject();
try {
pload.put("username", username);
pload.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, ENDPOINT, pload, response->{
Gson gson = new Gson();
JSONArray data = response.optJSONArray("data");
Log.d("RESPONSE", response.toString());
}, error -> {
String responseBody = null;
try {
responseBody = new String(error.networkResponse.data, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("ERROR", responseBody);
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("X-Tidal-Token", "q--------------------------k");
headers.put("Content-Type", "application/json");
return headers;
}
};
mqueue.add(request);
LogCat:
D/REQUEST: body: {"username":"b-------@gmail.com","password":"p------"} ___ headers: {X-Tidal-Token=q---------------k, Content-Type=application/json} ___ request.tostring: [ ] https://api.tidalhifi.com/v1/login/username 0xcc20303d NORMAL null
E/Volley: [309] BasicNetwork.performRequest: Unexpected response code 400 for https://api.tidalhifi.com/v1/login/username
D/ERROR: {"status":400,"subStatus":1002,"userMessage":"password cannot be blank,username cannot be blank"}
正如您所见,有效载荷不是空的,所以我有点困惑。 Tidal 没有官方 API,但有一些我一直在使用的非官方包装器供参考,以下是一些使用代码的示例:
Javascript:
request({
method: 'POST',
uri: '/login/username?token=kgsOOmYk3zShYrNP',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
username: authInfo.username,
password: authInfo.password,
}
Java:
var url = baseUrl.newBuilder()
.addPathSegment("login")
.addPathSegment("username")
.build();
var body = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
var req = new Request.Builder()
.url(url)
.post(body)
.header(TOKEN_HEADER, token)
.build();
再次Java:
HttpResponse<JsonNode> jsonResponse = restHelper.executeRequest(Unirest.post(API_URL + "login/username")
.header("X-Tidal-Token", "wdgaB1CilGA-S_s2")
.field("username", username)
.field("password", password));
如果需要,我可以发布所有包装器的链接并提供用于测试的潮汐令牌(获取相当容易,您只需从潮汐桌面应用程序嗅探数据包)。我试过覆盖 getParams() 但这没有用。任何帮助表示赞赏!
【问题讨论】:
-
您尝试更改 Content-type 标头吗?在您的日志中,您使用的是
application/json,但在 JS 示例和第一个 java 示例中,Content-type 是application/x-www-form-urlencoded -
更改内容标头不起作用,但似乎这是一种不同类型的请求,我尝试了一些不同的方法都不起作用,我将如何编写请求这种格式?
-
是否需要使用 Volley 库?如果不切换到 OkHttp,您将能够像您的第一个 java 示例一样:square.github.io/okhttp
标签: java rest post android-volley