【问题标题】:Android: HttpClient remote vs. local serverAndroid:HttpClient 远程与本地服务器
【发布时间】:2012-09-19 05:33:06
【问题描述】:

我在连接到远程 Web 服务器、针对数据库运行 php 脚本时遇到问题。但是,当我将同一个应用程序指向在我的机器上运行的本地 Web 服务器时,事情就不起作用了。

这是我用于连接到远程 Web 服务器的代码(它需要身份验证):

(所有网络代码都在 AsyncTask 类中完成。)

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringBuilder authentication = new   
    StringBuilder().append("frankh").append(":").append("vriceI29");
result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
nameValuePairs.add(new BasicNameValuePair("date", date));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

对于不使用身份验证的本地服务器的连接,我将这些行注释掉:

//StringBuilder authentication = new   
//    StringBuilder().append("frankh").append(":").append("vriceI29");
//result = Base64.encodeBytes(authentication.toString().getBytes());
//httppost.setHeader("Authorization", "Basic " + result);

但是,我收到两个不同的错误,具体取决于我如何将 url 表述到本地 Web 服务器。

如果我使用这个网址:“http://localhost.shoppinglistapp/fetchlist.php”

我收到此错误:

Error in http connectionjava.net.UnknownHostException: localhost.shoppinglistapp

如果我跳过网址中的 http 部分,我会收到此错误:

Error in http connectionjava.lang.IllegalStateException: Target host must not be null,
or set in parameters.

我在这里做错了什么?远程服务器是 Linux Apache 服务器,本地服务器是 IIS 7。本地服务器应该只是在我没有或没有互联网连接时工作,所以这并不重要,但我讨厌不知道为什么事情不起作用。

【问题讨论】:

  • 你是在设备还是模拟器上测试?
  • localhost.shoppinglistapp/fetchlist.php 这应该是localhost/shoppinglistapp/fetchlist.php吗?

标签: android httpclient


【解决方案1】:

如果您通过本地模拟器进行测试,您需要使用 10.0.2.2 而不是“localhost”。

Referring to localhost from the emulated environment

【讨论】:

  • 谢谢,这就是解决方案 :)
猜你喜欢
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 2015-04-07
  • 2023-03-19
相关资源
最近更新 更多