HttpUrlConnection post请求

public static String gethtmlPost(String cookie, String htmltype,
            String httpurl, String version,String MethodType,String Param,Boolean changeline)
            throws IOException {
        
        URL urlx = new URL(httpurl);
        HttpURLConnection uc = (HttpURLConnection) urlx.openConnection();
         //建立输入流,向指向的URL传入参数
       
        uc.setDoOutput(true);     //需要输出
        uc.setDoInput(true);      //需要输入
        uc.setUseCaches(false);   //不允许缓存
        uc.setRequestMethod(MethodType);      //设置POST方式连接
        
        if (cookie != null && !cookie.trim().equals("")){
            uc.setRequestProperty("Cookie", cookie);
        }
         
        //设置请求属性
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        uc.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        uc.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36");
        if(MethodType.equals("POST")){
        DataOutputStream dos=new DataOutputStream(uc.getOutputStream());
        dos.write(Param.getBytes("utf-8"));  //否则中文乱码
        dos.flush();
        dos.close();
        }
        //获得响应状态
        int resultCode=uc.getResponseCode();
        StringBuffer sb=new StringBuffer();
        if(HttpURLConnection.HTTP_OK==resultCode){
           
            String readLine=new String();
            BufferedReader responseReader=new BufferedReader(new InputStreamReader(uc.getInputStream(),htmltype));
            while((readLine=responseReader.readLine())!=null){
                if (changeline!=null && changeline == false){
                     sb.append(readLine);
                }else{
                     sb.append(readLine).append("\n");    
                }
         
            }
            responseReader.close();
          
        }
        
        
        return sb.toString();  
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值