I have an API which allows post request to register new users.
I'm using djoser library for authentication in the API.
It works in browser but when I try making this post request in my android project.I get 401 unauthorized response, I don't know what is wrong with my request!?
private static String makeHttpRequest(URL url, String info) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
//write to the stream
outputStream = urlConnection.getOutputStream();
byte[] input = info.getBytes(Charset.forName("UTF-8"));
outputStream.write(input, 0, input.length);
urlConnection.connect();
//read the response
if (urlConnection.getResponseCode() == 200) {
authenticated = true;
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
return jsonResponse;
}