Http 模拟form表单提交Post请求

    xiaoxiao2021-04-11  19

    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; }
    转载请注明原文地址: https://ju.6miu.com/read-666826.html

    最新回复(0)