API返回错误。"字段不能为空"

问题描述 投票:1回答:1

我目前正在尝试与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);

The LogCat:

 D/REQUEST: body: {"username":"[email protected]","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(),但没有成功。任何帮助是感激的

java rest post android-volley
1个回答
0
投票

你使用了错误的格式来发送请求,你在使用Json的时候,你需要的是Url编码的格式,链接供参考。在后置请求中发送form-urlencoded参数android volley。一个解决方案。一个字符串请求。

final String api = "http://api.url";
final StringRequest stringReq = new StringRequest(Request.Method.POST, api, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
  //do other things with the received JSONObject
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
               }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> pars = new HashMap<String, String>();
                    pars.put("Content-Type", "application/x-www-form-urlencoded");
                    return pars;
                }

                @Override
                public Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> pars = new HashMap<String, String>();
                    pars.put("Username", "usr");
                    pars.put("Password", "passwd");
                    pars.put("grant_type", "password");
                    return pars;
                }
            };
  //add to the request queue
  requestqueue.AddToRequestQueue(stringReq);
© www.soinside.com 2019 - 2024. All rights reserved.