0

更新: これらの問題は、301 リダイレクトを実行するリバース プロキシが原因でした。URL をリダイレクト先に変更すると、問題が修正されました。

Android から Web サービスへの 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 に答える