• JAVA实现HTTP请求


    目前JAVA实现HTTP请求的方法用的最多的有两种:

    一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;

    另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。

    公司用的第二种HttpURLConnection,该方式返回数据是String类型,接收后需要用 JsonUtil.getObject(resultStr, ResultInfo.class);获取json对象

    in.readLine()得到的就是返回值,不需要循环就行:
     public static String sendPost(String serverUrl, String param, String charsetName, String contentType) {
            ResultInfo resultInfo = null;
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                long t1 = System.currentTimeMillis();
                URL url = new URL(serverUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);    // 可以发送数据
                conn.setDoInput(true);    // 可以接收数据
                conn.setRequestMethod("POST");    // POST方法
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                // 必须注意此处需要设置UserAgent,否则google会返回403
                conn.setRequestProperty
                        ("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                if(contentType != null){
                    conn.setRequestProperty("Content-Type", contentType);
                }
                if (charsetName != null) {
                    conn.setRequestProperty("Accept-Charset", charsetName);
                    conn.setRequestProperty("contentType", charsetName);
                }
                conn.setConnectTimeout(HttpUtils.TIMEOUT);
                conn.setReadTimeout(HttpUtils.TIMEOUT_MAX);
                conn.connect();
                // 写入的POST数据
                OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), charsetName);
                osw.write(param);
                osw.flush();
                osw.close();
    
                // 读取响应数据
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), charsetName));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                long t2 = System.currentTimeMillis() - t1;
                logger.info("发送 POST 请求serverUrl={},param={},耗时:{}", serverUrl, param, t2);
            } catch (Exception e) {
                logger.error("发送 POST 请求出现异常!serverUrl={},param={}", serverUrl, param, e);
            }finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    logger.error("异常信息=", ex);
                }
            }
    
            return result;
        }

  • 相关阅读:
    128. 最长连续序列( 数组背诵题吧)
    310. 最小高度树 (拓扑排序 bfs)
    797. 所有可能的路径(图的遍历)
    sql关于group by和max函数一起使用的坑(同理,求部门最高工资)
    计算正逆序
    886. 可能的二分法(dfs bfs二部图判断)
    java实现RSA加密
    读取logback日志
    logback进阶
    词法分析笔记2
  • 原文地址:https://www.cnblogs.com/zhaoyanhaoBlog/p/11508957.html
Copyright © 2020-2023  润新知