我正在尝试使用用 Laravel 4 制作的 API Rest,但是当我尝试创建新资源(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);
但是,我得到的是 index
函数的响应,而不是进入 Laravel 资源的 store
函数。
我将此代码放入我的 index
中以检查 http 方法:
dd("索引:".$_SERVER['REQUEST_METHOD']);
并返回“GET”,所以我的代码有问题。一切都适用于 PUT
和 GET
http 方法,只有 POST
我确认空 body 不是问题,因为我尝试过。
有人可以尝试一下我的代码吗?
我完全绝望了。我只要求你,测试我的代码并引导我走向正确的方向,拜托...
最佳答案
您应该看看retrofit 。该库将使您的 api 调用更加清晰,并避免您在 HttpURLConnection 之上构建请求时遇到的所有问题。
编辑: 如果您想自己执行请求,请查看 this邮政。这个问题和你的非常相似。看来您需要在请求正文中发送数据。顺便说一句,通过 header 发送参数并不是一个好方法。我认为可能存在一些长度限制,而且您可能会遇到一些编码问题。
header 应该用于 http 相关信息或仅用于 token 。 您应该使用正文来发送数据。数据大多数时候使用 json/xml 或 httpurlencoded 参数发送。
编辑2:
我在 wamp 服务器上尝试了与您完全相同的代码,并且 $_SERVER['REQUEST_METHOD'] 返回了 POST。所以这个问题可能来自您的服务器。尝试使用 post man chrome plugin 测试您的服务器 api看看你的错误来自哪一边。
关于php - HttpURLConnection setRequestMethod 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31050918/