做一个简单的http请求

做一个简单的http请求

java中有事需要去用http做远程请求,获取参数:
这里举一个实际用到的简单http连接,请求参数为:param,返回参数为:fileName

public class HttpConnection {
    @Value("${user.ip}")
    private String ip;
    @Value("${user.port}")
    private Integer port;
    public String getResult(String param){
        String url = "http://"+ip+port+"app/planMng/qryAttachmentsById?factsId="+param;
        String fileName = "";
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream=null;

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("accept","'/'");
            connection.setRequestProperty("connection","Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;)");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();

             inputStream = connection.getInputStream();

            byte[] buffer = new byte[1024];
            int num = -1;
            while ((num = inputStream.read(buffer)) !=-1){
                byteArrayOutputStream.write(buffer,0,num);
            }
            byte[] bs = byteArrayOutputStream.toByteArray();
            String string = new String(bs,"UTF-8");
            System.out.println(string);
            JSONObject parseObject = (JSONObject) JSONArray.parse(string);
            JSONObject redata = parseObject.getJSONObject("retData");
            JSONArray a = redata.getJSONArray("data");
            JSONObject nameObject = (JSONObject) a.get(0);
            fileName = nameObject.getString("name");
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();
            inputStream.close();
            connection.disconnect();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != byteArrayOutputStream){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }
}

简单实用
记得当年在银行做的一个直连请求,示例:

public class HttpCommonUtils {
    private static final Log log = LogFactory.getLog(HttpCommonUtils.class);
    private static final String CONSTANT_ENCODING = "UTF-8";

    /**
     * 发送HttpPost请求
     *
     * @param requestUrl   请求地址
     * @param requestParam 请求参数
     * @return 成功:返回json字符串<br/>
     */
    public static String postRequest(String requestUrl, Map<String, Object> requestParam) {
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        StringBuffer result = new StringBuffer();
        log.info("获取请求地址:" + requestUrl);
        log.info("获取请求参数:" + requestParam);
        try {
            // Post请求的url,与get不同的是不需要带参数
            URL url = new URL(requestUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //从连接读取数据,默认是true
            connection.setDoInput(true);
            /**
             * 设置是否向connection输出,因为这个是post请求,参数要放在
             *http正文内,因此需要设为true
             **/
            connection.setDoOutput(true);
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            //设置本次连接是否自动重定向
            connection.setInstanceFollowRedirects(true);
            // 默认是 GET方式
            connection.setRequestMethod("POST");
            /**
             *  配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
             *  意思是正文是urlencoded编码过的form参数
             */
            connection.setRequestProperty("Accept-Charset", CONSTANT_ENCODING);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json;charset=" + CONSTANT_ENCODING);
            /**
             * 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
             * 要注意的是connection.getOutputStream会隐含的进行connect
             */
            connection.connect();
            //设置数据发送格式
            outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), CONSTANT_ENCODING);
            outputStreamWriter.write(JSONObject.toJSONString(requestParam));

            outputStreamWriter.flush();
            outputStreamWriter.close();
            outputStreamWriter = null;
            //获取返回
            inputStream = connection.getInputStream();
            //此处读取字节流
            inputStreamReader = new InputStreamReader(inputStream, CONSTANT_ENCODING);
            bufferedReader = new BufferedReader(inputStreamReader);

            String line = "";
            while (null != (line = bufferedReader.readLine())) {
                result.append(line);
            }
            log.info("接收到的返回参数:" + result);
            inputStream.close();
            inputStream = null;
            inputStreamReader.close();
            inputStreamReader = null;
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神雕大侠mu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值