Search code examples
javaandroidhttpurlconnectionxserver

HttpURLConnection - Response Code: 400 (Bad Request) Android Studio -> xserve


So I'm trying to connect to our database via Xserve, AT the moment I'm trying to access the token for the user. I'm using the correct username and password along with the context type and grant type; I know this because I've tried the same POST method via googles postmaster extension. For whatever reason when I try the same thing on Android, at least what I think is the same, it gives me a 400 response code and doesn't return anything.

Here's the code used to connect:

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;
    }

I haven't stored the result into the JSONObject yet as I'll use that later, but I expected some kind of output via the "Log.v".

Is there anything that stands out?


Solution

  •  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);
    
            }
        }
    

    this works, although I've moved it to it's own function now. changed the input type to a HashMap