2

I'm trying to consume an API rest made with Laravel 4, but when I try to create a new resource (store, POST method) I get response of index function (GET method).

I don't know whats happening with my code:

public static String sendInfo(HashMap<String, String> headers) {
    URL url;
    HttpURLConnection urlConnection = null;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        url = new URL(headers.get("URL"));

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(headers.get("method"));

        // Loop hashmap and apply headers
        for (HashMap.Entry<String, String> entry : headers.entrySet()) {
            // I only need the headers with real information. URL and method headers are only for the setRequestMethod and the object URL.
            if (!entry.getKey().equals("URL") && !entry.getKey().equals("method")) {
                urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();
        } else {
            Log.d("sendInfo", "ERROR " + headers.get("URL") + "  STATE: " + urlConnection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            urlConnection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("sendInfo", "ERROR DISCONNECT: " + e.getLocalizedMessage());
        }
    }
    Log.d("RESPONSE", "SERVER RESPONSE: "+stringBuilder.toString());

    return stringBuilder.toString();
}

I call this method as follow:

HashMap<String, String> headers = new HashMap<String, String>();
headers.put("URL", "http://foo.com/api/person/");
headers.put("method", "POST");
headers.put("name", "Jason");
headers.put("lastname", "Harrison");
sendInfo(headers);

​But intead of entry in the store function of my Laravel resource, I'm getting the response of the index​ function.

​I put this code in my index to check the http method:

​dd("Index: ".$_SERVER['REQUEST_METHOD']);​

​And returns "GET", so something is wrong in my code​​. All works well with PUT and GET http methods, it only fail with POST

I confirm that the empty body is not the problem, being that I try that.

May somebody could try my code, please?

I'm fully desperate. I only ask you, test my code and guide me in the right direction, please...

MartaGom
  • 501
  • 6
  • 27
  • please, do not repost [the same question](http://stackoverflow.com/questions/31048921/httpurlconnection-setrequestmethod-doesnt-work-with-post) – Selvin Jun 25 '15 at 12:54
  • 1
    @Selvin i wanted to improve my explanation. I remove the old question. But .. Why the downvote? – MartaGom Jun 25 '15 at 12:55
  • @Selvin I have done something wrong? – MartaGom Jun 25 '15 at 12:58
  • then you should use **edit** ... and about the question ... where you are sending the body of the post? – Selvin Jun 25 '15 at 13:20
  • @Selvin I dont know that... I only send headers. Its a problem? Thanks – MartaGom Jun 25 '15 at 13:21
  • I don't know how Laravel or PHP reacts on empty POST ... log `headers.get("method")` if it is really "post" after `urlConnection.setRequestMethod(headers.get("method"))` then it is a server side ... – Selvin Jun 25 '15 at 13:22
  • 1
    @Selvin With PUT works well and i do not use the body too. Is weird... I dont know whats hapenning – MartaGom Jun 25 '15 at 13:24
  • @Selvin I tried that before. Returns "POST" so I dont know what happen. Thanks for comment, im desperate. X_x – MartaGom Jun 25 '15 at 13:27

1 Answers1

3

You should take a look at retrofit. This lib would make your api call much more cleaner and avoid all those problems you encounter building your request on top of HttpURLConnection.

EDIT: If you want to do the request by yourself take a look at this post. The problem is very similar to yours. It seems that you need to send data in you request body. Btw sending your parameters via headers isn't a good way to go. I think there might be some lenght restriction plus you might encounter some encoding issues.

Headers should be used for http related information or just for tokens. You should use body to send your data. Data are most of the time sent using json/xml or httpurlencoded params.

Edit 2:

I tried your exact same code with a wamp server and $_SERVER['REQUEST_METHOD'] returned POST. So maybe this issue commes from your server. Try testing you server api with post man chrome plugin to see from which side you error comes from.

Community
  • 1
  • 1
user2641570
  • 804
  • 8
  • 20
  • I want to implement it by myself. Thanks! – MartaGom Jun 25 '15 at 13:22
  • Thanks for your edit. I tried with that but still with the same problem... I wish to open a bounty x_x can you think any solution? You could try my code please? Puff. Im desperate – MartaGom Jun 25 '15 at 16:18