Android:尽管发送了 POST,但始终在服务器上获取 GET
我正在尝试使用 POST 方法从我的 Android 应用程序发送数据。然而在 服务器始终将其识别为 GET。我使用 Rails 应用程序作为网络 服务。这是我的 Android 代码片段:
URI uri = new URI(hostName);
HttpPost httpRequest = new HttpPost(uri);
httpRequest.addHeader("Accept", "application/json");
httpRequest.addHeader("Content-Type", "application/json");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
httpRequest.setEntity(new UrlEncodedFormEntity(pairs));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
我做错了什么吗?感谢您的帮助。
I am trying to send data using POST method from my android apps. However in
the server it is always recognized as GET. I am using Rails apps as the web
service. Here is the snippet of my Android code:
URI uri = new URI(hostName);
HttpPost httpRequest = new HttpPost(uri);
httpRequest.addHeader("Accept", "application/json");
httpRequest.addHeader("Content-Type", "application/json");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
httpRequest.setEntity(new UrlEncodedFormEntity(pairs));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
Have I done anything wrong? Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 Android 代码看起来不错,请确保您的日志不显示 POST 的 301 重定向代码,尽管显示 GET 的 200 代码。奇怪的是,根据您的主机配置,可能会出现这种情况。
例如,您可能会看到类似这样的内容:
此处 GET 未重定向(代码 200),但 POST 已重定向(代码 301)。如果发生这种情况,那么您需要使用 .htaccess 或其他配置选项覆盖重定向设置。
You're android code looks fine, make sure your log doesn't show a 301 redirect code for POST despite showing a 200 code for GET. Strangely, this can be the case depending on your host configuration.
e.g. You might see something like this :
Here the GET was not redirected (code 200), but the POST was (code 301). If this is happening then you need to override your redirect settings using a .htaccess or other configuration options.
您被重定向了吗?我怀疑,如果您尝试 POST 到域 A,而域 A 将您重定向到域 B,则您的请求将转换为 GET 请求。我遇到了同样的问题,直到我决定直接在 POST 请求中使用服务器的 IP 地址,而不是使用重定向到 IP 的字母名称。
Were you being redirected? I suspect that if you try to POST to domain A that redirects you to domain B, your request will be turned in to a GET request. I had the same problem until I decided to use the server's IP address in the POST request directly, instead of using a alphabet name that redirects to the IP.