Java发送请求到php页面

Java发送网络请求到PHP,并将PHP处理内容返回到Java程序。

public static String genSig(String ... params){
        String requestPath="http://XXXX/index.php";//XXXX表示ip地址,可以查看本机或服务器的ip地址。
        URL url;
        HttpURLConnection phpConn=null;
        try {
            //建立连接
            url= new URL(requestPath);
            phpConn= (HttpURLConnection) url.openConnection();

            //连接属性
            phpConn.setDoOutput(true);//使用URL连接进行输出
            phpConn.setDoInput(true);//使用URL连接进行输入
            phpConn.setUseCaches(false);
            phpConn.setRequestMethod("POST");

            String requestParams="appID="+params[0]+"&secret="+params[1]+"&roomID="+params[2]
                    +"&userID="+params[3]+"&expire="+params[4];  //请求参数拼接
            byte[] requestParamsBytes=requestParams.getBytes("UTF-8");

            //设置请求属性
            phpConn.setRequestProperty("Content-length",""+requestParamsBytes.length);
            phpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            phpConn.setRequestProperty("Connection","Keep-Alive");//维持长连接
            phpConn.setRequestProperty("Charset","UTF-8");
            phpConn.connect();//连接

            //建立输出流,写入数据
            OutputStream outputStream=phpConn.getOutputStream();
            outputStream.write(requestParamsBytes);
            outputStream.close();
            //获取响应状态
            int response=phpConn.getResponseCode();

            if(HttpURLConnection.HTTP_OK==response){//连接成功
                StringBuffer sb=new StringBuffer();
                String readLine;
                BufferedReader bufferedReader;
                bufferedReader=new BufferedReader(new InputStreamReader(phpConn.getInputStream(),"UTF-8"));
                while (null!=(readLine=bufferedReader.readLine())){
                    sb.append(readLine).append("\n");
                }
                bufferedReader.close();
                return sb.toString();
            }
            else{
                System.out.println("连接失败!");	
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if(null!=phpConn){//关闭连接
                phpConn.disconnect();
            }
        }
        return null;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值