【Android】 HttpClient 发送REST请求
直接po代码吧,第一个是一个枚举类型的类,是四种rest http请求,get/post/put/delete:
public enum HttpRequestMethod { HttpGet { @Override public HttpUriRequest createRequest(String url) { return new HttpGet(url); } }, HttpPost { @Override public HttpUriRequest createRequest(String url) { return new HttpPost(url); } }, HttpPut { @Override public HttpUriRequest createRequest(String url) { return new HttpPut(url); } }, HttpDelete { @Override public HttpUriRequest createRequest(String url) { return new HttpDelete(url); } }; public HttpUriRequest createRequest(String url) { return null; } }
接下来是一个HttpUtil类,作用是可以指定http请求类型、访问的url和带的参数:
public class HttpUtil { private static final String DEFAULT_LOCAL_ENCODE = "UTF-8"; private static final String DEFAULT_REMOTE_ENCODE = "UTF-8"; private static final int HTTP_200 = 200; public static HttpClient httpClient = new DefaultHttpClient(); static { httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, Integer.valueOf(5000)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, Integer.valueOf(3000)); } public static final String BASE_URL = "localhost:8080/demo/login"; public static String sendRequest(HttpRequestMethod requestMethod, String url,final Map<String ,String> params) throws Exception { final HttpUriRequest request = requestMethod.createRequest(url); if(params != null) { ((HttpEntityEnclosingRequest)request).setEntity( new UrlEncodedFormEntity(MapToPair(params), DEFAULT_REMOTE_ENCODE)); } FutureTask<String> task = new FutureTask<String>( new Callable<String>() { @Override public String call() throws Exception { HttpResponse response = httpClient.execute(request); if(response.getStatusLine().getStatusCode() == HTTP_200) { return EntityUtils.toString(response.getEntity(), DEFAULT_LOCAL_ENCODE); } return "访问失败"; } } ); new Thread(task).start(); return task.get(); } static List<NameValuePair> MapToPair(Map<String, String> map) { final List<NameValuePair> pairList = new ArrayList<NameValuePair>(); for (String key : map.keySet()){ pairList.add(new BasicNameValuePair(key, map.get(key))); } return pairList; } }
里面用到了跟多线程有关的FutureTask类,不是很了解先用着,感觉多线程、并发相关的东西还是挺多的而且很重要,这里使用多线程是因为可能会有IO阻塞,这样会导致主界面挂掉。
回想一下,在移动应用程序中,长时间的操作(如网络、文件或长的计算)不应该在主系统线程上完成。相反,应在一个单独的工作线程中执行它们。阻塞系统线程会对应用程序的用户界面的响应能力产生负面影响,有可能导致强行关闭您的应用程序。
调用的话很简单,只需要:
HttpUtil.sendRequest(HttpRequestMethod.HttpPost, url, map);
其中map是一个HashMap<String, String>类型的。
大功告成~虽然很简单,但是毕竟第一次写,学习到不少,当然也想知道HttpClient底层是如何实现的,肯定是封装了socket但是内部一定有一些很有意思的东西。
另外,关于TCP/IP也是水深的可以,接下来要做聊天了,稍微了解了一下长连接和短链接,以及心跳机制和轮询机制,以后会慢慢都写到博客。