0

I am sending a string to server using HttpPost. This string is a JSONObject thath i have previously converted to String So far everything is working properly... It must be sent with content-type "application / json".

To send it, convert my String to a StringEntity and add to httpPost.setEntity (my_string) ... The problem is that the server tells me that does not recognize the data (is ready to receive the JSONObject converted to String)

In my code, I use a log to know the value of the String before converting to StringEntity, and this is the result:

String: {"Gender":"male","User":"Pedro","Email":"[email protected]","Language":"English"}

However, when I convert this String to StringEntity, the result of the Log, instead of being the same, it is as follows:

String: org.apache.http.entity.StringEntity@16a4bc74

Why?

I do not know what I'm doing wrong ...

I searched and I found many examples, I think I'm doing it correctly ... I do not understand the error. Why the string, when converted to StringEntity not maintained values?

I have tried many examples, such as http://hmkcode.com/android-send-json-data-to-server/, and many more.

This is my code.

I appreciate the help very much.

Greetings.

public static JSONObject makeServiceCall(String url, JSONObject params) {

try {

    Log.i("dmode", "LLegan los valores:" + " " + params);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpEntity httpEntity = null;
    HttpResponse httpResponse = null;
    HttpPost httpPost = new HttpPost(url);


    if (params != null) {

        String conversion = params.toString();

        Log.i("dmode", "JSONBoject to String" + " " + conversion);

        StringEntity se;
        se = new StringEntity(conversion);

        Log.e("dmode", "String to StringEntity" + " " + se);

        // Set HTTP parameters
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(se);

    }

    String response = null;

    httpResponse = httpClient.execute(httpPost);
    httpEntity = httpResponse.getEntity();
    response = EntityUtils.toString(httpEntity);

    try {
        jObject = new JSONObject(response);
    } catch (Exception e) {

    }

    Log.i("dmode", "Devolución" + jObject);

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

return jObject;

}

1 Answer 1

1

Try using URL Connection :

public JSONObject readJSONFromURL(String urlString, JSONObject param){
        String response = null;
        JSONObject jObject = null;
        try {           
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("dmode", param.toString()));
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();
            conn.connect();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            response = getStringFromInputStream(in);
            jObject = new JSONObject(response);
        } catch (UnsupportedEncodingException e) {
            Log.e("ERROR", "UnsupportedEncodingException " + e.toString());
        }  catch (IOException e) {
            Log.e("ERROR", "IOException " + e.toString());
        } catch (JSONException e) {
            Log.e("ERROR", "JsonException: " + e.toString());
        }
        return jObject;
    }

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");
            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
        return result.toString();
    }

    private String getStringFromInputStream(InputStream is) { 
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

This can be a good solution @abhishesh , but as I can apply the Content-type "application / json "? conn.setRequestProperty("Content-Type", "application/json"); not work
you dont need to apply content type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.