Java 发送POST请求示例

注意:使用OutputStream 时,POJO类需实现序列化

package com.bmp.sdk.util;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created with IDEA
 *
 * @ Author:wangm
 * @ Date:Created in  2018/11/20 16:19
 * @ Description:发送Http通用类
 */
public class HttpUtil {
    private static final String DEFAULT_CHARSET = "UTF-8";

    /** 读取超时 */
    private static final int    DEFAULT_READ_TIMEOUT = 120000;

    /** 连接超时 */
    private static final int	DEFAULT_CONN_TIMEOUT = 20000;
    /**
     * @param url
     * @param params
     * @return
     * @throws IOException
     * @作用 使用urlconnection
     */
    public static JSONObject sendPost(String url, String params) throws IOException {
        OutputStream out = null;
        BufferedReader reader = null;
        String response = "";
        try {
            URL httpUrl = null; 
            //创建URL
            httpUrl = new URL(url);
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset="+DEFAULT_CHARSET);
            conn.setConnectTimeout(DEFAULT_CONN_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            conn.setUseCaches(false);//设置不要缓存
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //POST请求
            out = conn.getOutputStream();
            out.write(params.getBytes(DEFAULT_CHARSET));
            out.flush();
            //读取响应
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),DEFAULT_CHARSET));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), DEFAULT_CHARSET);
                response += lines;
            }
            reader.close();
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        JSONObject json = JSONObject.parseObject(response);
        return json;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值