我一直试图从Android应用程序进行RESTful POST调用已有好几天了。我已经尝试了许多不同的方法,到目前为止我还没有运气。似乎有几个问题,首先我添加了
<uses-permission android:name="android.permission.INTERNET" />
到清单,以确保我可以使用套接字/网络。
然后我尝试了以下不同的方法尝试接听电话:
System.setProperty("java.net.useSystemProxies", "true");
HttpURLConnection c = (HttpURLConnection) new URL(url+mUrl).openConnection();
c.setUseCaches(false);
c.setDoOutput(true);
c.setRequestMethod("POST");
c.setRequestProperty("Content-length","9");
c.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
c.setRequestProperty("Accept","application/json");
c.setRequestProperty("Authorization", "basic " + Base64.encodeBytes((username+":"+password).getBytes()));
c.connect();
OutputStream os = c.getOutputStream();
os.write("mode=Push".getBytes());
os.flush();
os.close();
我不确定Android是否自动处理任何所需的代理设置,我尝试添加,但在此方法中,c.connect()只会永久挂起,没有异常,没有超时,没有返回。
下一个方法如下:
DefaultHttpClient httpClient = getClient();
HttpResponse response = null;
HttpPost postMethod = new HttpPost(this.url + mUrl);
postMethod.addHeader("Content-type", "application/x-www-form-urlencoded");
postMethod.addHeader("Accept","application/json");
postMethod.addHeader("Authorization", "basic " + Base64.encodeBytes((username+":"+password).getBytes()));
if (hm == null) return null;
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
Iterator<String> it = hm.keySet().iterator();
String k, v;
while (it.hasNext())
{
k = it.next();
v = hm.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(postMethod);
现在,当我从工作中运行它,在代理/防火墙后面或者当我在家中运行它时,我会返回UnknownHostException,然后我得到一个Challenge空异常。 这都是在模拟器Droid 1.6应用程序下运行。我有Fiddler2正在运行,我根本没有看到80端口出来的任何东西......帮助:)