Valentina Pakhomova
Valentina Pakhomova

Reputation: 11

Can't send a correct POST request in Java (Android Studio)

I'm creating an app for asking/answering questions. I have a problem with POST request when I ask questions.

I've tried to use something like this in terminal

curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "[email protected]"}' http://your-app-name.herokuapp.com/contacts

and it worked good.

But when I try to send a POST request in AndroidStudio my parameters (such as name, lastname, email and etc) won't send. I tried to use https://github.com/kevinsawicki/http-request. The request is send (I know that because it shows the date of the request) but without any parameters.

What should be changed in my code so it would work correctly?

Map<String, String> data = new HashMap<String, String>();
data.put("firstName", "Gena");
data.put("lastName", "Bukin");
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created())
System.out.println("User was created");

Upvotes: 0

Views: 2963

Answers (4)

dpr
dpr

Reputation: 10972

Basically your curl requests sends the user data in JSON format in the request body. Your Java code tries to send the data in the request as form data which is something different and probably not accepted by the server.

You might need to change your code to use the HttpRequest.send(...) method instead of form:

JSONObject json = new JSONObject();
json.put("firstName", "Gena");
json.put("lastName", "Bukin");
json.put("email", "[email protected]");

HttpRequest
    .post("https://safe-citadel-91138.herokuapp.com/questions")
    .contentType("application/json")
    .send(json.toString());

Furthermore in the curl call you are using accesses a different url than in the Java snippet http://your-app-name.herokuapp.com/contacts vs https://safe-citadel-91138.herokuapp.com/questions maybe you are talking to the wrong endpoint as well?

You might want to take a look at some Java to JSON mapping library like gson for the transformation of your Java objects to proper JSON or use Android's JSONObject class.

UPDATE:

  • Added link to gson for JSON mapping
  • Updated code snippet to use JSONObject for the JSON mapping

Upvotes: 0

Andan H M
Andan H M

Reputation: 793

Try like this..

Map<String, Object> params = new LinkedHashMap<>();
params.put("firstName", "Gena");
params.put("lastName", "Bukin");


JSONObject jsonObject = POST("https://safe-citadel-91138.herokuapp.com/questions", params);
    /**
         * Method allows to HTTP POST request to the server to send data to a specified resource
         * @param serverURL URL of the API to be requested
         * @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another
         * returns response as a JSON object
         */
        public JSONObject POST(String serverURL, Map<String, Object> params) {
            JSONObject jsonObject = null;
            try {
                URL url = new URL(serverURL);

                Log.e(TAG, params.toString());
                StringBuilder postData = new StringBuilder();

                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                Log.e("POST", serverURL + ":" + params.toString());
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);
                connection.setUseCaches(false);
                connection.setDoOutput(true);
                connection.getOutputStream().write(postDataBytes);
                connection.connect();

                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                }
                jsonObject = new JSONObject(sb.toString());
            } catch (Exception e) {
                //e.printStackTrace();
            }
            return jsonObject;
        }

Upvotes: 1

Raghavendra
Raghavendra

Reputation: 2303

I have just tried to create an User and it worked. You can refresh the link u have shared to check the created User.

This is what I have tried

String endPoint= "https://safe-citadel-91138.herokuapp.com/questions";
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(endPoint);
            post.addHeader("Content-Type", "application/json");
            JSONObject obj = new JSONObject();

            obj.put("firstName", "TESTF");
            obj.put("lastName", "TESTL");
            obj.put("email", "[email protected]");

            StringEntity entity = new StringEntity(obj.toString()); 
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
}catch (Exception e){

        }

UPDATE

BTW I have used json jar from this link

Upvotes: 0

Nisarg
Nisarg

Reputation: 1388

try this hope it'll work

public JSONObject getJSONFromUrl(String url_, JSONObject jsonObject) {

    try {
        URLConnection urlConn;
        DataOutputStream printout;

        URL url = new URL(url_);
        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setConnectTimeout(30000);
        urlConn.setReadTimeout(30000);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("Accept", "application/json");

        urlConn.setRequestProperty("Authorization", "token"); // If Applicable 
        urlConn.connect();
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.writeBytes(jsonObject.toString());
        printout.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        printout.close();
        reader.close();
        json = sb.toString();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Applog.e("response", jObj + "");
    return jObj;

}

Upvotes: 0

Related Questions