HttpURLConnection getHeaderFields().get("Content-Type") 获得网页编码问题

本文探讨了使用HttpURLConnection获取网页编码的有效性和局限性。指出并非所有网站都会通过Content-Type头提供字符编码信息,因此建议采用分析网页内容的方式确保准确获取编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于有些网页,使用HttpURLConnection 的 getHeaderFields().get("Content-Type")  能正确获得网页的编码。但有些网页却不能正确地获得,通过查看服务器返回的头信息,发现了问题所在,

http://it.sohu.com/20090711/n265142337.shtml 响应头
null : [HTTP/1.0 200 OK]
Date : [Sun, 12 Jul 2009 14:42:20 GMT]
Vary : [Accept-Encoding]
Expires : [Sun, 12 Jul 2009 14:44:20 GMT]
Last-Modified : [Sun, 12 Jul 2009 14:40:10 GMT]
Via : [1.0 33107306.44707239.41988739.sohu.com:80 (squid)]
Content-Type : [text/html]
Connection : [close]
Server : [Apache/1.3.39 (Unix) mod_gzip/1.3.26.1a]
X-Cache : [MISS from 33107306.44707239.41988739.sohu.com]
Cache-Control : [max-age=120]

红色的部分是关键,服务器给予的反应并没有把字符编码加进来。所以,使用上面的办法是没有办法获得编码的。

而对于另一个网页,却有字符编辑,见下:

http://news.xinhuanet.com/world/2009-04/27/content_11267743.htm 响应头
null : [HTTP/1.0 200 OK]
ETag : ["47f8ae1-4909-fb3f2080"]
Very : [Accept-Encoding]
Content-Length : [4973]
Last-Modified : [Mon, 27 Apr 2009 09:29:22 GMT]
Connection : [keep-alive]
Powered-By-ChinaCache : [CNC-LY-7-3BB HIT, CNC-QD-K-33U HIT]
X-Cache : [HIT from news48.xinhuanet.com]
Server : [Apache]
Date : [Sat, 27 Jun 2009 07:22:49 GMT]
Content-Encoding : [gzip]
Via : [1.0 news48.xinhuanet.com:80 (squid/2.6.STABLE16)]
Content-Type : [text/html; charset=GB2312]
Accept-Ranges : [bytes]


综上所述,要获得一个网页的编码,上述办法不一定满足条件,最保险的办法是分析网页内容。

package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; public class HttpTest { private HttpURLConnection hc = null; private static final String oneUrlString = "http://xxx.jsp"; private static final String twoUrlString = "http://xxx.action"; public String getSessionId() { String sessionId = ""; try { URL url = new URL(oneUrlString); hc = (HttpURLConnection) url.openConnection();//默认的用GET提交 hc.setDoOutput(true); hc.connect(); Map map = hc.getHeaderFields(); //得到Cookie的所有内容,包括SESSIONID,在进行下次提交的时候 直接把这个Cookie的值设到头里头就行了 //淡然只得到SESSIONID也很简单的 ,但是有时候Set-Cookie的值有几个的 List list = (List) map.get("Set-Cookie"); if(list.size() == 0||list == null) { return null; } StringBuilder builder = new StringBuilder(); for(String str : list) { sessionId = builder.append(str).toString(); } hc.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sessionId; } public String getResponseContext(String parameters) { String responseContext = ""; try { URL url = new URL(twoUrlString); hc = (HttpURLConnection) url.openConnection();//使用POST提交 hc.addRequestProperty("Cookie", getSessionId()); hc.setDoOutput(true); hc.connect(); OutputStream out = hc.getOutputStream(); //参数是a=""&b=""这样拼接的一个串 out.flush(); out.close(); out.write(parameters.getBytes(),0,parameters.getBytes().length); InputStream in = hc.getInputStream(); InputStreamReader reader = new InputStreamReader(in,"gb2312"); BufferedReader read = new BufferedReader(reader); StringBuilder builder = new StringBuilder(); String str = ""; while((str = read.readLine()) != null) { builder = builder.append(str); } read.close(); reader.close(); in.close(); hc.disconnect(); responseContext = builder.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseContext; } }
### 使用 `java.net.URLConnection` 设置 Content-Type 为 multipart/form-data 为了通过 `java.net.URLConnection` 发送 `multipart/form-data` 类型的数据,需要手动构建请求体并设置合适的头部信息。下面是一个完整的示例来展示这一过程: ```java import java.io.*; import java.net.*; public class MultipartFormDataExample { private static final String CRLF = "\r\n"; private static final String BOUNDARY_PREFIX = "--"; public void sendMultipartForm(String urlString, File file) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置连接属性 connection.setDoOutput(true); // 表明此URL连接打算写入数据 connection.setRequestMethod("POST"); String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; // 自定义边界字符串 // 添加Content-Type头,并指定boundary connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream outputStream = connection.getOutputStream()) { PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); // 构建文件部分的内容 StringBuilder sb = new StringBuilder(); sb.append(BOUNDARY_PREFIX).append(boundary).append(CRLF); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF); sb.append("Content-Type: application/octet-stream").append(CRLF); sb.append(CRLF); writer.println(sb.toString()); FileInputStream inputStream = null; byte[] buffer = new byte[4096]; int bytesRead; try { inputStream = new FileInputStream(file); while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); writer.append(CRLF).flush(); // 文件结束后的CRLF // 结束标志 writer.append(BOUNDARY_PREFIX).append(boundary).append(BOUNDARY_PREFIX).append(CRLF).flush(); InputStream responseStream = new BufferedInputStream(connection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream)); String line; while((line = reader.readLine()) != null){ System.out.println(line); } reader.close(); } finally { if(inputStream!=null){ inputStream.close(); } } } } } ``` 上述代码展示了如何创建一个多部件表单上传请求[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值