Android请求ASP.NET Web API

22 浏览
0 Comments

Android请求ASP.NET Web API

我正在尝试从Android应用程序向ASP.NET Web API发出GET请求。该API应该返回一个带有一些用户的JSON对象。在浏览器中调用API时一切正常,但是在尝试从Android应用程序调用时没有任何反应。我查看了Fiddler,没有发送任何请求。

这是我用于发出调用的代码:

class GetData extends AsyncTask{
        @Override 
        protected String doInBackground(String... params){
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            try{
            HttpGet get = new HttpGet("http://10.0.2.2:38216/api/user");
            response = client.execute(get);
            if(response != null){
                InputStream inStream = response.getEntity().getContent();
                String message = convertToString(inStream);
                return message;
            }
        }
        catch(Exception exp){
            Log.d("Error message!", exp.toString());
        }
        return null;
    }
}

如果您对我做错了什么有任何想法或提示,将不胜感激!

0
0 Comments

问题的出现原因:Android应用程序中的HttpClient不会自动使用在其他应用程序(例如Web浏览器)中配置的代理。需要通过设置DEFAULT_PROXY或使用System.setProperty()为http.proxy*或https.proxy*来教会HttpClient使用代理。

解决方法:根据你的情况,你需要设置http.proxy*来使用代理。这样,你就可以在Android应用程序中使用Fiddler进行请求。你可以参考这个问题的解答:stackoverflow.com/questions/214308/…

这样,你就可以解决Android应用程序请求ASP.NET Web API时无法在Fiddler中显示请求的问题了。

0