编辑: 感谢一些使用过的芒果我编辑了我的方法,但仍然没有得到它的消除?标记。
public String makeHttpGetRequestUtf8(String urlStr) throws IOException {
String result = "";
try {
URL url = new URL(urlStr);
//BufferedReader brIn = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); //<--- Tried this first but didn't help.
BufferedReader brIn = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)); //<-- This also didn't help :(
String line = "";
while ((line = brIn.readLine()) != null)
result += line;
}catch (Exception e){
Log.e("HTT_GET", "Failed to make httpGetRequestUtf8: " + e);
}
String afterDecode = URLDecoder.decode(result, "UTF-8");
return afterDecode;
}
在android中我尝试了两个httpGet方法来获取api的响应。两者都返回带有问号的内容,这意味着没有utf-8支持。
浏览器上的相同api调用返回UTF-8支持的文本。 答案是在json。
httpGet 1:
public String makeHttpGetRequest(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStreamReader isr = new InputStreamReader(con.getInputStream());
String response = readUntilEndOfStream(isr);
isr.close();
return response;
}
private String readUntilEndOfStream(InputStreamReader isr) throws IOException {
StringBuffer data = new StringBuffer();
int character = isr.read();
while (character != END_OF_STREAM) {
data.append((char) character);
character = isr.read();
}
return data.toString();
}
这会返回带有问号的回复。
httpGet 2:
public String makeHttpGetRequestUtf8(String urlStr) throws IOException {
String result = "";
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream isr = con.getInputStream();
// convert inputstream to string
if(isr != null)
result = convertInputStreamToString(isr);
else
result = "Could not make httpGetResul success";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
// convert inputstream to String
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
同样的故事。
我认为我在编码问题上存在一些原则性错误。 谢谢你的提示。
答案 0 :(得分:0)
要转换InputStream,您可以使用以下内容:
$insert_query
或在java 7中你可以做到
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
编辑:
您还可以尝试使用InputStreamReader(它将检测HTTP响应的编码):
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
如果它不起作用,可能需要在响应之前设置编码:
String responseBody = EntityUtils.toString(entity);