HttpURLConnection setRequestMethod not working as expected

I'm trying to use an API built with Laravel 4, but when I try to create a new resource ( store

, POST method), I get a response from a function index

(GET method).

I don't know what's going on 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 am calling this method like this:

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 instead of typing into the functions of store

my Laravel resource, I am getting the response from the function index

.

I put this code in mine index

to test the http method:

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

And it returns "GET", so something is wrong in my code. Everything works well with methods PUT

and GET

http, it only fails with an errorPOST

I confirm that empty body is not a problem as I am trying to do this.

Can someone try my code?

I am completely desperate. I'm only asking you to check my code and point me in the right direction please ...

+3


source to share


1 answer


You should take a look at retrofit . This lib will make your api call much cleaner and avoid all the problems you run into building your request on top of HttpURLConnection.

EDIT: If you'd like to make a request yourself, take a look at this post. The problem is very similar to yours. It seems that you need to send data to the request body. By the way, sending your parameters via headers is not the best way. I think there may be some kind of length limitation and you might run into some encoding issues.

Headers should be used for http related information or just for tokens. You must use a body to send your data. Data is most often sent using json / xml or httpurlencoded parameters.



Edit 2:

I tried your exact code with wamp server and $ _SERVER ['REQUEST_METHOD'] returned POST. So maybe this problem is with your server. Try testing the api server with the post man chrome plugin to see which side you receive the message from.

+3


source







All Articles