HttpURLConnection — Код ответа: 400 (неверный запрос) Android Studio -> xserve

Итак, я пытаюсь подключиться к нашей базе данных через Xserve, В данный момент я пытаюсь получить доступ к токену для пользователя. Я использую правильное имя пользователя и пароль вместе с типом контекста и типом гранта; Я знаю это, потому что я пробовал тот же метод POST через расширение постмастера Google. По какой-то причине, когда я пробую то же самое на Android, по крайней мере то, что я думаю, то же самое, он дает мне код ответа 400 и ничего не возвращает.

Вот код, используемый для подключения:

private HttpURLConnection urlConnection;

@Override
    protected Boolean doInBackground(Void... params) {
        Boolean blnResult = false;
        StringBuilder result = new StringBuilder();
        JSONObject passing = new JSONObject();

        try {
            URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");

            // set up connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            // set up parameters to pass
            passing.put("username", mEmail);
            passing.put("password", mPassword);
            passing.put("grant_type", "password");

            // add parameters to connection
            OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(passing.toString());


            // If request was good
            if (urlConnection.getResponseCode() == 200) {
                blnResult = true;
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(urlConnection.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                reader.close();
            }

            //JSONObject json = new JSONObject(builder.toString());
            Log.v("Response Code", String.format("%d", urlConnection.getResponseCode()));
            Log.v("Returned String", result.toString());

        }catch( Exception e) {
            e.printStackTrace();
        }
        finally {
            urlConnection.disconnect();
        }

        return blnResult;
    }

Я еще не сохранил результат в JSONObject, так как воспользуюсь им позже, но я ожидал какой-то вывод через «Log.v».

Есть ли что-то, что выделяется?


person Zachary    schedule 22.03.2017    source источник
comment
пожалуйста, поделитесь своим запросом почтальона и ответом   -  person Ajinkya    schedule 22.03.2017
comment
тип_гранта = пароль   -  person Zachary    schedule 22.03.2017
comment
извините за комментарии, я пытался вернуть каретку, это то, что я пытаюсь воссоздать в андроиде   -  person Zachary    schedule 22.03.2017


Ответы (1)


 try {
        URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");

        parameters = new HashMap<>();
        parameters.put("username", mEmail);
        parameters.put("password", mPassword);
        parameters.put("grant_type", "password");

        set = parameters.entrySet();
        i = set.iterator();
        postData = new StringBuilder();

        for (Map.Entry<String, String> param : parameters.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }

            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        postDataBytes = postData.toString().getBytes("UTF-8");

        // set up connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        urlConnection.setRequestMethod("POST");
        urlConnection.getOutputStream().write(postDataBytes);

        // If request was good
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            reader = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
        }

        Log.v("Login Response Code", String.valueOf(urlConnection.getResponseCode()));
        Log.v("Login Response Message", String.valueOf(urlConnection.getResponseMessage()));
        Log.v("Login Returned String", result.toString());


        jsonObject = new JSONObject(result.toString());
        token = jsonObject.getString("access_token");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        urlConnection.disconnect();
        if (token != null) {
            jsonObject = driverInfo(token);

        }
    }

это работает, хотя теперь я переместил его в собственную функцию. изменил тип ввода на HashMap

person Zachary    schedule 28.03.2017