• HttpURLConnection和HttpClient的简单用法


    HttpURLConnection的简单用法:先通过一个URL创建一个conn对象,然后就是可以设置get或者是post方法,接着用流来读取响应结果即可

        String html = null;
            long startTime = System.currentTimeMillis();
            try {
                URL url = new URL("http://www.baidu.com/");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
    
                conn.setConnectTimeout(5 * 1000);
                if (conn.getResponseCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
    
                        html += line;
                    }
                    /*
                //第二种方法
              InputStream is = conn.getInputStream(); byte []buffer = new byte[is.available()]; is.read(); String result = new String(buffer);*/ } } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

    HttpClient的简单用法:

    /**
         * @param url
         * @return 1.页面源码;2.TimeOut;3.没正确响应,返回null
         */
        public String doHttpGet(String url) {
            String result = null;
            //通过url来创建httpGet对象
            HttpGet httpGet = new HttpGet(url);
            httpClient = new DefaultHttpClient();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
            try {
                httpResponse = httpClient.execute(httpGet);
                // 判断响应的状态码,200表示成功响应了请求
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 得到结果集
                    result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");
                    // result = new String(result.getBytes(),"utf-8");
                    //System.out.println(result);
                } else {
                    System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
                return "TimeOut";
            }
            return result;
        }
    
        /**
         * @param url
         * @param paramsList
         * @return 1.页面源码;2.TimeOut;3.没有响应,返回null
         */
        public String doHttpPost(String url, List<NameValuePair> paramsList) {
            String result = null;
            // 根据url创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);
            httpClient = new DefaultHttpClient();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
            try {
                // 设置HttpPost请求参数必须用NameValuePair对象
                httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
                // 发送post请求
                httpResponse = httpClient.execute(httpPost);
                // 判断响应的状态码,200表示成功响应了请求
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(httpResponse.getEntity());
                    //System.out.println(result);
                } else {
                    System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println("UnsupportedEncodingException");
            } catch (ParseException e) {
                System.out.println("ParseException");
            } catch (IOException e) {
                return "TimeOut";
            }
            return result;
        }

    工具类NetManager

    package com.kale.mycmcc.net;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.CoreConnectionPNames;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    
    public class NetManager {
        public static int TIME_OUT = 4 * 1000;
    
        private HttpResponse httpResponse = null;
        private HttpClient httpClient;
    
        /**
         * @param url
         * @return 1.页面源码;2.TimeOut;3.没正确响应,返回null
         */
        public String doHttpGet(String url) {
            String result = null;
            //通过url来创建httpGet对象
            HttpGet httpGet = new HttpGet(url);
            httpClient = new DefaultHttpClient();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
            try {
                httpResponse = httpClient.execute(httpGet);
                // 判断响应的状态码,200表示成功响应了请求
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 得到结果集
                    result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");
                    // result = new String(result.getBytes(),"utf-8");
                    //System.out.println(result);
                } else {
                    System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
                return "TimeOut";
            }
            return result;
        }
    
        /**
         * @param url
         * @param paramsList
         * @return 1.页面源码;2.TimeOut;3.没有响应,返回null
         */
        public String doHttpPost(String url, List<NameValuePair> paramsList) {
            String result = null;
            // 根据url创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);
            httpClient = new DefaultHttpClient();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
            try {
                // 设置HttpPost请求参数必须用NameValuePair对象
                httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
                // 发送post请求
                httpResponse = httpClient.execute(httpPost);
                // 判断响应的状态码,200表示成功响应了请求
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(httpResponse.getEntity());
                    //System.out.println(result);
                } else {
                    System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println("UnsupportedEncodingException");
            } catch (ParseException e) {
                System.out.println("ParseException");
            } catch (IOException e) {
                return "TimeOut";
            }
            return result;
        }
    
    /*    *//**
         * 使用正则表达式过滤HTML标记
         *//*
        private String filterHtml(String source) {
            if (null == source) {
                return "";
            }
            return source.replaceAll("</?[^>]+>", "").trim();
        }
    
        private void showToast(Context mContext, String message, int flag) {
            Looper.prepare();
            Toast.makeText(mContext, message, flag).show();
            Looper.loop();
        }*/
    
    }
  • 相关阅读:
    定时器
    WPF拖动总结
    将两个不同进程的窗口设置为父子关系
    Docker私有仓库管理
    Dockerfile创建zabbix监控体系
    Dockfile自动创建discuz论坛和可道云
    Docker的自动构建镜像
    Docker简介
    Mapreduce
    分布式文件系统与HDFS
  • 原文地址:https://www.cnblogs.com/tianzhijiexian/p/3984926.html
Copyright © 2020-2023  润新知