【发布时间】:2015-06-25 12:50:57
【问题描述】:
我正在尝试使用由 Laravel 4 制作的 API 休息,但是当我尝试创建新资源(store,POST 方法)时,我得到了index 函数(GET 方法)的响应。
我不知道我的代码发生了什么:
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();
}
我称这个方法如下:
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);
但是在我的 Laravel 资源的 store 函数中输入,我得到了 index 函数的响应。
我将这段代码放在我的index 中以检查http方法:
dd("Index: ".$_SERVER['REQUEST_METHOD']);
并返回“GET”,所以我的代码有问题。一切都适用于PUT 和GET http 方法,只有POST 失败
我确认空的身体不是问题,因为我尝试过。
有人可以试试我的代码吗?
我完全绝望了。我只问你,测试我的代码并引导我朝着正确的方向前进,请...
【问题讨论】:
-
请不要转发the same question
-
@Selvin 我想改进我的解释。我删除了旧问题。但是.. 为什么投反对票?
-
@Selvin 我做错了什么?
-
那么您应该使用 edit ...关于问题...您将帖子正文发送到哪里?
-
@Selvin 使用 PUT 效果很好,我也不使用身体。很奇怪......我不知道发生了什么
标签: php android rest laravel-4 httpurlconnection