• java使用HttpURLConnection发送Post数据


        public static byte[] readInputStream(InputStream inStream) throws Exception {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    
            byte[] buffer = new byte[10240];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
    
            return outStream.toByteArray();
        }
        
        public static String sendPost(String urlStr, String dataStr, String paramsStr) {
            String result = "";
    
            try {
                byte[] data = dataStr.getBytes("UTF-8");
    
                URL url = new URL(urlStr);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("Content-Length", String.valueOf(data.length));
                conn.setRequestProperty("Content-Type", "text/xml");
                conn.connect();
    
                OutputStream  out = conn.getOutputStream();
                out.write(data);
                out.flush();
                out.close();
    
                System.out.println(conn.getResponseCode());
    
                if (conn.getResponseCode() == 200) {
                    System.out.println("连接成功");
                    InputStream in = conn.getInputStream();
                    byte[] data1 = readInputStream(in);
                    result = new String(data1);
    
                } else {
                    System.out.println("连接失败");
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return result;
        }
  • 相关阅读:
    AudioToolbox学习(转)
    ios5键盘问题
    何时使用self.
    ios判断邮箱,手机号码,车牌号是否合法(正则表达)
    将图片重新绘制
    在UITableViewCell中获取所在的行数以及去除选中状态
    根据UIView获取其UIViewController
    在iOS中将string转成UTF8编码
    SQL提高性能
    oracle创建口令文件
  • 原文地址:https://www.cnblogs.com/ziwuxian/p/13371572.html
Copyright © 2020-2023  润新知