0

更新:这些问题是由执行 301 重定向的反向代理引起的。将 url 更改为重定向的目标解决了该问题。

我正在努力从 android 向网络服务发出 POST 请求。

我有一个在 IIS7 上运行的 Web 服务,其内容如下:

<OperationContract()> _
<Web.WebInvoke(BodyStyle:=WebMessageBodyStyle.Bare, Method:="POST", RequestFormat:=WebMessageFormat.Xml, ResponseFormat:=WebMessageFormat.Xml, UriTemplate:="HelloWorld")> _
    Function HelloWorld() As XmlElement 

当我从 Firefox 向此 url 发送 POST 请求时,它按预期工作。

当我使用以下代码从 Android 设备发出请求时:

String sRequest = "http://www.myserviceurl.com/mysevice/HelloWorld";
ArrayList<NameValuePair> arrValues = new ArrayList<NameValuePair>();
arrValues.add(new BasicNameValuePair("hello", "world"));

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(sRequest);
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setEntity(new UrlEncodedFormEntity(arrValues));
HttpResponse response = httpClient.execute(httpRequest);

我收到 Method Not Allowed 405 响应,并且在查看 IIS 日志时,对该 url 的请求显示为“GET”。

如果我将请求的目标更改为回显 $_SERVER['REQUEST_METHOD'] 的 PHP 脚本,则输出为 POST。

Web 服务的 web.config 具有 GET、HEAD 和 POST 作为动词。

有什么我忽略的吗?

4

2 回答 2

2

我必须通过禁用自动重定向然后捕获响应代码和重定向 URL 并重新执行 POST 来实现解决方法。

// return false so that no automatic redirect occurrs
httpClient.setRedirectHandler(new DefaultRedirectHandler()
{
    @Override
    public boolean isRedirectRequested(HttpResponse response, HttpContext context)
    {
        return false;
    }
});

然后当我发出请求时

response = httpClient.execute(httpPost, localContext);
int code = response.getStatusLine().getStatusCode();
// if the server responded to the POST with a redirect, get the URL and reexecute the  POST
if (code == 302 || code == 301)
{
    httpPost.setURI(new URI(response.getHeaders("Location")[0].getValue()));
    response = httpClient.execute(httpPost, localContext);
}
于 2011-10-02T03:26:45.723 回答
0

尝试:

DefaultHttpClient http = new DefaultHttpClient();
    HttpResponse res;
    try {
        HttpPost httpost = new HttpPost(s);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));

        res = http.execute(httpost);


        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }
        res = null;
        httpost = null;
        String ret = new String(baf.toByteArray(),encoding);
        return  ret;
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    }
于 2011-04-04T14:10:25.637 回答