开发者

RESTful HTTP call from Android

I've been trying to make a RESTful POST call from an Android app for several days now. I've tried a number of different methods and I haven't had any luck so far. There seem to be several issues, Firstly I added

<uses-permission android:name="android.permission.INTERNET" /> to the manifest to ensure I could work with sockets/network.

Then I've tried the following different methods to try and get a call out:

    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();

I'm not sure if Android automatically deals with any required proxy settings, I tried adding that in but in this method the c.connect() just hangs forever, no exception, no timeout, no return.

The next method was as follows:

        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 = ne开发者_如何转开发w 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); 

This now either returns UnknownHostException when I run it from work, behind a proxy/firewall or when I run it from home then I get a Challenge empty exception. This is all running under the emulator, Droid 1.6 app. I've got Fiddler2 running and I'm not seing anything coming out over port 80 at all... Help :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜