使用Java For Android的HTTP API请求

我找到了一个我想玩的API,因为我是免费的。 我想问一下,如果我想使用API​​开发Android应用程序,而API是基于HTTP协议的(RESTful),我该如何使用HTTPClient对象呢?

我有一般要求信息。

HEAD /authenticate/ HTTP/1.1 Host: my.api.com Date: Thu, 17 Jul 2008 14:52:54 GMT X-SE-Client: some-value X-SE-Accept: xml X-SE-Auth: 90a6d325e982f764f86a7e248edf6a660d4ee833 

如果成功,上述的反应将是如此。

 HTTP/1.1 200 OK Date: Thu, 17 Jul 2008 14:52:55 GMT Server: MyApi Content-Length: 795 Connection: close Content-Type: text/xml 

我知道如何使用HTTPClient发送HTTP请求但是它是否会在请求中添加额外的标头和其他不必要的东西? 如何查看HTTPClient对象发出的请求? 我想简单地请求在telnet中传递文本。

您应该能够在Android中使用HttpClient来完成您的需要。 我刚刚完成了Android与ASP.NET MVC 3站点集成的第一部分,我必须说 – 它非常轻松。 我使用Json作为我的数据交换格式。

通过在构建请求后设置调试点,可以准确查看标头的外观。 这是一些示例代码(请记住它只是示例代码 – 不是完整的实现)。

该类由与UI线程不同的线程调用:

 public class RemoteDBAdapter { public String register(String email, String password) throws Exception { RestClient c = new RestClient("http://myurl/Account/Register"); c.AddHeader("Accept", "application/json"); c.AddHeader("Content-type", "application/json"); c.AddParam("Email", email); c.AddParam("Password", password); c.Execute(RequestMethod.POST); JSONObject key = new JSONObject(c.getResponse()); return key.getString("status"); } } 

使用此类构建您的请求并执行它:

 public class RestClient { public enum RequestMethod { GET, POST } private ArrayList  params; private ArrayList  headers; private String url; private int responseCode; private String message; private String response; public String getResponse() { return response; } public String getErrorMessage() { return message; } public int getResponseCode() { return responseCode; } public RestClient(String url) { this.url = url; params = new ArrayList(); headers = new ArrayList(); } public void AddParam(String name, String value) { params.add(new BasicNameValuePair(name, value)); } public void AddHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value)); } public void Execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""; if(!params.isEmpty()){ combinedParams += "?"; for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8"); if(combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + combinedParams); //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url); break; } case POST: { HttpPost request = new HttpPost(url); //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } JSONObject jo = new JSONObject(); if(!params.isEmpty()){ for (int i = 0; i < params.size();i++) { jo.put(params.get(i).getName(),params.get(i).getValue()); } StringEntity se = new StringEntity(jo.toString()); se.setContentType("text/xml"); se.setContentEncoding( new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); request.setEntity(se); //request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } executeRequest(request, url); break; } } } private void executeRequest(HttpUriRequest request, String url) { //HttpClient client = new DefaultHttpClient(); HttpClient client = HttpClientFactory.getThreadSafeClient(); HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } 

编辑:

哦,你和HttpClientFactory:

 // Should be thread safe public class HttpClientFactory { private static DefaultHttpClient client; public synchronized static DefaultHttpClient getThreadSafeClient() { if (client != null) return client; client = new DefaultHttpClient(); ClientConnectionManager mgr = client.getConnectionManager(); HttpParams params = client.getParams(); client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params); return client; } } 

REST使用的格式与旧的SOAP方法相比要严格得多。

如果你想传递一个字符串或类似的东西,我建议在REST中使用JSON。 使用XML的REST用于更复杂的结构,如嵌套的XML有效负载等等。 JSON也可能会快得多。 Android中也内置了对JSON的支持。