IIS似乎认为Android HttpPost是一个GET

时间:2011-04-04 13:47:19

标签: android iis-7 http-post operationcontract

更新:这些问题是由执行301重定向的反向代理引起的。将网址更改为重定向的目标位置可解决此问题。

我正在努力向Android发送一个POST请求到Web服务。

我在IIS7上运行了一个Web服务,其中包含以下内容:

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

当我从Firefox向此网址发送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);

我得到一个不允许的方法405响应,当查看IIS日志时,对此URL的请求显示为“GET”。

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

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

有什么我忽略的吗?

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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();
    }