user3448282 user3448282 - 1 year ago 336
Android Question

Send JSON as a POST request to server by AsyncHttpClient

I want to be able to send JSON as a POST to my localhost server by AsyncHttpClient. 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);
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);, "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth", entity, "application/json", new JsonHttpResponseHandler() {
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
try {
Log.i("SER", "HERE!");
String login = obj.getString("login");
int ID = obj.getInt("id");

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

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();

looks ok:


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?

Answer Source

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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download