关闭

Http 模拟form表单提交Post请求

标签: Http 模拟form表单提交Post请
1343人阅读 评论(0) 收藏 举报
分类:
private static Logger log = LoggerFactory.getLogger(HttpPostUtil.class);

public static  String reqXinyi(String urls, String appkey,String data,String sign) throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    String param= null;
    String b = null;
    try {
        param = "appKey="+ URLEncoder.encode(appkey, "UTF-8")+"&data="+URLEncoder.encode(data, "UTF-8")+"&sign="+URLEncoder.encode(sign, "UTF-8");
        log.info("拼接请求参数param:"+param);
    } catch (UnsupportedEncodingException e) {
        log.error("拼接请求参数错误");
        e.printStackTrace();
    }
        log.info("开始发送请求");
        URL url = new URL(urls);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) connection;
        // 设置请求方法为POST
        httpConn.setRequestMethod("POST");
        // 设置是否需要输出
        httpConn.setDoOutput(true);
        // 设置是否需要允许输入
        httpConn.setDoInput(true);
        // 设置请求属性
        httpConn.setRequestProperty("Content-Length",String.valueOf(param.getBytes().length));
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // 向服务器端写数据
        OutputStream out = httpConn.getOutputStream();
        out.write(param.getBytes("UTF-8"));
        out.close();
        // 接收服务器返回的数据
        InputStream in = httpConn.getInputStream();
        ByteArrayOutputStream resp = new ByteArrayOutputStream();
        byte[] tempbytes = new byte[100];
        int byteread = 0;
        while ((byteread = in.read(tempbytes)) != -1) {
            resp.write(tempbytes, 0, byteread);
        }
        b = new String(resp.toByteArray());
        log.info("调用接口返回:{}",b);
        return b;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18206次
    • 积分:1418
    • 等级:
    • 排名:千里之外
    • 原创:129篇
    • 转载:8篇
    • 译文:0篇
    • 评论:1条
    最新评论