util之HttpURLConnection接口发送工具

其他注解可以查看这个链接
http://www.blogjava.net/supercrsky/articles/247449.html

public
class RESTUtil { protected static final Logger logger = LoggerFactory.getLogger(RESTUtil.class); /** * @param requestUrl * @param sendType * @param params * @return */ public StringBuffer getRESTData(String requestUrl, String sendType, String params) { logger.info("===============================>请求路径" + requestUrl); logger.info("===============================>发送参数" + params); StringBuffer jsonString = new StringBuffer(); try { // 生成HttpURLConnection对象 URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置是否从httpUrlConnection读入,默认情况下是true; connection.setDoInput(true); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false; connection.setDoOutput(true); // Post 请求不能使用缓存 //connection.setUseCaches(false); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) // connection.setRequestProperty("Content-type", "application/x-java-serialized-object"); // 设定请求的方法为"POST",默认是GET // connection.setRequestMethod("POST"); connection.setRequestMethod(sendType); connection.setConnectTimeout(50000); // 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, // connection.connect(); // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, // 所以在开发中不调用上述的connect()也可以)。 OutputStream writer = connection.getOutputStream(); writer.write(params.toString().getBytes()); // 关闭流对象 writer.close(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = br.readLine()) != null) { jsonString.append(line); } // 关闭流对象 br.close(); connection.disconnect(); logger.info("===============================>返回结果" + jsonString.toString()); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } return jsonString; } }

 全量

package com.xxx.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RESTUtil {

    protected static final Logger logger = LoggerFactory.getLogger(RESTUtil.class);

    public RESTUtil() {

    }

    public StringBuffer getRESTData(String requestUrl, String sendType, String params) {
        StringBuffer jsonString = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            logger.info("===============================>请求路径" + requestUrl);
            logger.info("===============================>发送参数" + params);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(sendType);
            connection.setConnectTimeout(50000);
    
            OutputStream writer = connection.getOutputStream();
       
            writer.write(params.toString().getBytes());
            writer.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();
            logger.info("===============================>返回结果" + jsonString.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return jsonString;
    }

    public StringBuffer getRESTData(String requestUrl, String sendType, Map<String, Object> params) {
        StringBuffer jsonString = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            logger.info("===============================>请求路径" + requestUrl);
            logger.info("===============================>发送参数" + params);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(sendType);
            connection.setConnectTimeout(50000);
    
            OutputStream writer = connection.getOutputStream();
            String temp = params.toString().substring(1);
            temp = temp.substring(0, temp.length() - 1);
            writer.write(temp.getBytes());
            writer.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();
            logger.info("===============================>返回结果" + jsonString.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return jsonString;
    }

    /**
     * 传递参数 获取接口数据
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方法
     * @param accept
     *            默认为application/json
     * @param verb
     *            统一定义为“Add”,“Get”,“Modify”等,且大小写敏感。
     * @param noun
     *            用来定义对象的类型。
     * @param contentType
     *            默认为application/json
     * @param param
     *            参数拼接
     * @return
     */
    public synchronized static String getRestData(String requestUrl, String requestMethod, String accept, String verb, String noun, String contentType, String param) {
        HttpURLConnection connection = null;
        StringBuffer jsonString = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(requestMethod);

            connection.setRequestProperty("Accept", accept);
            connection.setRequestProperty("verb", verb);
            connection.setRequestProperty("noun", noun);
            connection.setRequestProperty("Content-Type", contentType);

            OutputStream writer = connection.getOutputStream();
            writer.write(param.getBytes());
            writer.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
        } catch (ConnectException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e1.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (connection != null)
                connection.disconnect();
        }
        return jsonString.toString();
    }

}

 

posted @ 2020-10-29 10:10  爱跳舞的程序员  阅读(314)  评论(0编辑  收藏  举报