【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阻塞,这样会致使主界面挂掉。并发

回想一下,在移动应用程序中,长时间的操做(如网络、文件或长的计算)不该该在主系统线程上完成。相反,应在一个单独的工做线程中执行它们。阻塞系统线程会对应用程序的用户界面的响应能力产生负面影响,有可能致使强行关闭您的应用程序。socket

调用的话很简单,只须要:ide

HttpUtil.sendRequest(HttpRequestMethod.HttpPost, url, map);

其中map是一个HashMap<String, String>类型的。post

 

 

大功告成~虽然很简单,可是毕竟第一次写,学习到很多,固然也想知道HttpClient底层是如何实现的,确定是封装了socket可是内部必定有一些颇有意思的东西。学习

另外,关于TCP/IP也是水深的能够,接下来要作聊天了,稍微了解了一下长链接和短连接,以及心跳机制和轮询机制,之后会慢慢都写到博客。url

相关文章
相关标签/搜索