Bri*_*ins 1 asp.net android http asp.net-web-api
我有一个奇怪的问题。我从我的 Android 应用程序中调用 ASP.NET Web API。我可以从应用程序发出 POST 请求,没有任何问题。但是,当我去发出 GET 请求时,请求返回“400 bad request invalid hostname”。这很奇怪,因为我可以发出 POST 请求,而不是 get 请求。我使用的 URL 是http://10.0.2.2/webapp/api/controllername(10.0.2.2,因为 android 模拟器使用 127.0.0.1;这是已发布的解决方法)。我确实启用了互联网权限。
我当前正在调试 Web API,并且可以调试 post 请求。我可以在 Internet Explorer 中手动输入获取请求的 URL,然后访问服务器。这就是我知道它起作用的方式。我有一个 application_beginrequest 的处理程序,只是为了查看我什至正在访问服务器,它是用于发布请求的。但我什至从未看到服务器收到 get 请求。
为了发出 Android GET 请求,我使用了以下内容(添加了带有附加信息的注释)。
//Creation of get request
HttpGet request = new HttpGet(url); //correct URL; verified
for(NameValuePair h : headers)
{
//6 headers added; verified OK
request.addHeader(h.getName(), h.getValue());
}
//Calls method shown below
return executeRequest(request, url);
private ResponseInformation executeRequest(HttpUriRequest request, String url) throws Exception
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
//Get the response and check the code/message
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
ResponseInformation info; // just a DTO for my needs
if (entity != null) {
InputStream instream = entity.getContent();
//Response is an XML document listing the 400 error information
response = convertStreamToString(instream);
info = new ResponseInformation(responseCode, response, message);
instream.close();
}
else
info = new ResponseInformation(responseCode, message);
return info;
}
.
.
}
Run Code Online (Sandbox Code Playgroud)
所以我不确定是谁在拒绝?为什么我会收到此错误?它永远不会命中 Application_BeginRequest,因此它永远不会到达我的 Web API 服务,但 POSTS 会......太奇怪了。
我使用 Web API 自托管时遇到同样的问题,无法发送 GET 或 POST 请求。
400 Invalid Hostname如果传入主机和Host标头与配置的 IIS 或自主机主机名不同,则Web API 会生成此消息。我在主机和 Android 模拟器中使用(WireShark 无法在 Windows 中监控环回 IP)。这RawCaptcpdumpHost头以某种方式自动设置为 10.0.2.2。
您无法使用 Fiddler 看到此问题,因为您可以在没有 10.0.2.2 解决方法的情况下获取 127.0.0.1。
只有当我们使用 10.0.2.2 特殊 IP 并且 Android 应用程序中的 Http 客户端库自动将Host标头设置为该 IP 时,才会发生这种情况。就我而言,我使用Retrofit. 由于Host标头 10.0.2.2 与 127.0.0.1 或 localhost 不同,因此 Web API 会生成 400 无效主机名。
然后我将Host标题覆盖为localhost:port,它就可以正常工作:
RestAdapter.Builder builder= new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
if (HOST.contains("10.0.2.2")) { // HOST = "http://10.0.2.2/api";
request.addHeader("Host", "localhost");
}
}
});
Run Code Online (Sandbox Code Playgroud)
只需确保HostAndroid 应用程序的标头正确即可。
| 归档时间: |
|
| 查看次数: |
3782 次 |
| 最近记录: |