THE CODE IN BELOW IS THE SOLUTION
I am trying to send a json object with multiple elements to a social media app to get a token(I need to provide username/password) and get a token. I searched all over SO and find some questions similar to this and try to implement them but with each of them it ends up with bad request(meaning not the expected json) Here is my last try with respect to this question. And I know it should return status code 200 because I tried it in rest advanced client. Sending a JSON HTTP POST request from Android
Here is the code I tried in various different ways.
HttpURLConnection urlConnection=null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("user-agent","Agent/1");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("username", mJidView.getText().toString());
jsonParam.put("password",mJidView.getText().toString());
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult =urlConnection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
Note: The application requires a header for user-agent and its signature is here.
- Request body:
{"username": "test", "password": "12345"}