9

I want to send JSON as a POST to my localhost server with LoopJ's AsndroidAsyncHttpt. I'm using this method: public void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) in my code but it doesn't work. Here is my code:

private void  loginUser() throws JSONException, UnsupportedEncodingException {
    String login = textLogin.getText().toString();
    String password = textPassword.getText().toString();

    JSONObject jsonObject = new JSONObject();
    if(Utility.isNotNull(login) && Utility.isNotNull(password)) {
        jsonObject.put("username", login);
        jsonObject.put("password", password);
        invokeWS(jsonObject);
    }
    else{
        Toast.makeText(getApplicationContext(), "Proszę wypełnić wszystkie pola!", Toast.LENGTH_LONG).show();
    }
}

private void invokeWS(JSONObject jsonObject) throws UnsupportedEncodingException {
    StringEntity entity = new StringEntity(jsonObject.toString());
    AsyncHttpClient client = new AsyncHttpClient();

    Log.i("SER", "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth" + entity);
    Log.i("SER", "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth" + jsonObject);

    client.post(getApplicationContext(), "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth", entity, "application/json", new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
            try {
                Log.i("SER", "HERE!");
                String login = obj.getString("login");
                int ID = obj.getInt("id");

                //user.setUserId(obj.getInt("userid"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            if (statusCode == 404) {
                Toast.makeText(getApplicationContext(), "404 - Nie odnaleziono serwera!", Toast.LENGTH_LONG).show();
            } else if (statusCode == 500) {
                Toast.makeText(getApplicationContext(), "500 - Coś poszło nie tak po stronie serwera!", Toast.LENGTH_LONG).show();
            } else if (statusCode == 403) {
                Toast.makeText(getApplicationContext(), "Podano niepoprawne dane!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), throwable.toString(), Toast.LENGTH_LONG).show();
            }
        }
    });
}

My Logs looks ok:

http://MY_IP_ADDRESS:8080/silownia_java/rest/login/authorg.apache.http.entity.StringEntity@384d6a6d
http://MY_IP_ADDRESS:8080/silownia_java/rest/login/auth{"username":"barni","password":"12345"}

But i get such error:

org.apache.http.client.HttpResponseException: Unsupported Media Type

Additionaly, I know that server doesn't get any request. So, what the cause could be?

Stephane Landelle
  • 6,990
  • 2
  • 23
  • 29
user3448282
  • 2,629
  • 3
  • 25
  • 47
  • 2
    yet another `localhost` ... Is the server on the device? – Selvin Jun 02 '15 at 11:24
  • Yes of course, I've changed it to localhost only for `stackoverflow`, because I didn't want to show my ip address. I know that server responds, because `get` requests works. – user3448282 Jun 02 '15 at 11:26
  • Sample response: `{"login":"barni","id":"1"}` but as far as I know, it's build with just string not JSON, it could be a problem? – user3448282 Jun 02 '15 at 11:27
  • On server side, the response is build like this: `return Response.status(200).entity("{\"login\":\""+user.getLogin()+"\",\"id\":\""+user.getUserId()+"\"}").build()` it could be a problem? – user3448282 Jun 02 '15 at 11:29
  • No, because of: *Additionaly, I know that server doesn't get any request* ... problem is localhost, just google for localhost+android(+emulator) – Selvin Jun 02 '15 at 11:30
  • But in program I don't use `localhost`, but my exact computer IP address and when I send `get` to server, I get response. – user3448282 Jun 02 '15 at 11:35
  • See this link, maybe help you! [Link][1]http://stackoverflow.com/questions/13052036/posting-json-xml-using-android-async-http-loopj – Madi Oct 14 '15 at 08:51

1 Answers1

13

I solved it, by adding header information to my entity object.

ByteArrayEntity entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
user3448282
  • 2,629
  • 3
  • 25
  • 47