java重定向设置header_java 到 php入门:header()重定向

header() 重定向用户,常用的有两种方式

1、 header('Location: url'); url重定向 相当于jsp sendRedirect()

2、header('Content-Type:text/html;charset=utf'); //页面编码

使用header函数必须注意:header函数之前不能有输出<?php

echo 'hello';

header('Location:header01.php'); // 重定向用户

?>

客户端运行结果:

helloWarning: Cannot modify header information - headers already sent

要解决这个问题可以调用ob_start()缓存<?php

ob_start(); // 缓存

echo 'hello';

header('Location:header01.php'); // 重定向用户

?>

程序正常运行缓存后再在运行。但是不推荐这么使用

需要注意的是php代码之前不能有html输出<?php

// <?php 上有空行

?>

Warning: Cannot modify header information - headers already sent2、header('Content-Type:text/html;charset=utf');

中文乱码的问题: php文件是什么编码,header的编码应该与其相同,否则会出现中文乱码

header('Content-Type:text/html;charset=utf-8');

echo '我是中文';

//浏览器显示:鎴戞槸涓枃

开始我的zend studio(或php页面编码)默认编码是gbk,而header编码为utf-8,所以出现了乱码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中,可以使用 `java.net.HttpURLConnection` 类来发送 HTTP 请求并设置 cookie。下面是一个简单示例: ```java import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; public class RedirectWithCookie { public static void main(String[] args) throws Exception { String urlString = "http://example.com"; URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置 cookie String cookie = "key=value"; conn.setRequestProperty("Cookie", cookie); // 允许重定向 conn.setInstanceFollowRedirects(true); conn.connect(); // 获取重定向后的 URL 和响应头部信息 int responseCode = conn.getResponseCode(); String location = conn.getHeaderField("Location"); Map<String, List<String>> headerFields = conn.getHeaderFields(); // 输出结果 System.out.println("Response code: " + responseCode); System.out.println("Location: " + location); System.out.println("Header fields:"); for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } ``` 在上面的示例中,我们首先创建了一个 `URL` 对象,然后使用 `HttpURLConnection` 打开连接。接着,我们设置 cookie,允许重定向,并连接到远程服务器。 如果重定向成功,我们可以使用 `getResponseCode()` 方法获取响应代码,使用 `getHeaderField("Location")` 方法获取重定向后的 URL,以及使用 `getHeaderFields()` 方法获取响应头部信息。最后,我们将这些信息输出到控制台。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值