来自Android的RESTful HTTP调用
几天来,我一直在尝试通过Android应用程序进行RESTful POST通话。我已经尝试了很多不同的方法,但到目前为止我还没有任何运气。首先,我补充道,似乎有几个问题来自Android的RESTful HTTP调用,android,restful-authentication,Android,Restful Authentication,几天来,我一直在尝试通过Android应用程序进行RESTful POST通话。我已经尝试了很多不同的方法,但到目前为止我还没有任何运气。首先,我补充道,似乎有几个问题 添加到清单中,以确保我可以使用套接字/网络 然后,我尝试了以下不同的方法来尝试和获得呼叫: System.setProperty("java.net.useSystemProxies", "true"); HttpURLConnection c = (HttpURLConnection) new URL(url+mUr
添加到清单中,以确保我可以使用套接字/网络
然后,我尝试了以下不同的方法来尝试和获得呼叫:
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);
DefaultHttpClient-httpClient=getClient();
HttpResponse响应=null;
HttpPost postMethod=新的HttpPost(this.url+mUrl);
postMethod.addHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
addHeader(“接受”、“应用程序/json”);
addHeader(“授权”、“基本”+Base64.encodeBytes((用户名+:“+密码).getBytes());
如果(hm==null)返回null;
尝试
{
List nameValuePairs=新的ArrayList(2);
迭代器it=hm.keySet().Iterator();
串k,v;
while(it.hasNext())
{
k=it.next();
v=hm.get(k);
添加(新的BasicNameValuePair(k,v));
}
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
response=httpClient.execute(postMethod);
现在,当我在工作中、在代理/防火墙后面运行它时,或者当我在家运行它时,返回UnknownHostException,然后得到一个质询空异常。
这一切都是在模拟器Droid 1.6应用程序下运行的。我已经运行了Fiddler2,而且我根本没有在端口80上发布任何东西……帮助:)快速问题:新的HttpPost(This.url+mUrl)看起来有点可疑。url和mUrl设置为什么?url是api的基础,mUrl只是相对的部分。所以它是“”;我已经通过emulator从我的家庭连接成功地使上述两种方法工作。我认为现在唯一的问题是工作网络中的防火墙/代理。我需要了解emulator中的任何设置,还是需要添加代码来指定代理?