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...