URL.openConnection()
サーバーから何かをダウンロードするために使用しています。サーバーは言う
Content-Type: text/plain; charset=utf-8
しかし、connection.getContentEncoding()
戻りますnull
。どうした?
URL.openConnection()
サーバーから何かをダウンロードするために使用しています。サーバーは言う
Content-Type: text/plain; charset=utf-8
しかし、connection.getContentEncoding()
戻りますnull
。どうした?
からURLConnection.getContentEncoding()
返される値は、ヘッダーからの値を返しますContent-Encoding
からのコードURLConnection.getContentEncoding()
/**
* Returns the value of the <code>content-encoding</code> header field.
*
* @return the content encoding of the resource that the URL references,
* or <code>null</code> if not known.
* @see java.net.URLConnection#getHeaderField(java.lang.String)
*/
public String getContentEncoding() {
return getHeaderField("content-encoding");
}
代わりに、aを実行connection.getContentType()
して Content-Type を取得し、Content-Type から文字セットを取得します。これを行う方法のサンプルコードを含めました....
String contentType = connection.getContentType();
String[] values = contentType.split(";"); // values.length should be 2
String charset = "";
for (String value : values) {
value = value.trim();
if (value.toLowerCase().startsWith("charset=")) {
charset = value.substring("charset=".length());
}
}
if ("".equals(charset)) {
charset = "UTF-8"; //Assumption
}
これは、メソッドがHTTPヘッダーgetContentEncoding()
の内容を返すように指定されているため、動作が文書化されていますが、これは例では設定されていません。Content-Encoding
このメソッドを使用してgetContentType()
、結果の文字列を独自に解析することも、 Apacheのようなより高度なHTTPクライアントライブラリを使用することもできます。
@Buhake Sindiからの回答への追加として。Guava を使用している場合は、手動で解析する代わりに次のことができます。
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();