用Android Studio3.6.2 開發程式,測驗提取網頁的時候某個網頁(https://www.iqiwx.com/book/67/67489/21683330.html)中文顯示為黑色菱形方塊加問號,如圖所示:
,已設定轉碼也不行,請問如何才能正確顯示?程式如下:
public class MainActivity extends AppCompatActivity {
EditText url;
Button send;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText) findViewById(R.id.url);
send = (Button) findViewById(R.id.send);
text = (TextView) findViewById(R.id.text);
//按鈕點擊事件
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//執行httpGet方法
httpGet();
}
});
}
private void httpGet() {
//開子執行緒網路請求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
String urls=url.getText().toString();
try {
URL url=new URL(urls);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
InputStream in=connection.getInputStream();
reader = new BufferedReader( new InputStreamReader(in));
StringBuilder response =new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
}
}).start();
}
//切換為主執行緒
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
String gbk;
byte[] utf8;
try {
gbk = new String(response.getBytes());
utf8 = gbk2utf8(gbk);
text.setText(new String(utf8,"UTF-8"));
//把獲取的網頁資料賦值給變數response,并設定給TextView控制元件
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
public byte[] gbk2utf8(String chenese){
char c[] = chenese.toCharArray();
byte [] fullByte =new byte[3*c.length];
for(int i=0; i<c.length; i++){
int m = (int)c[i];
String word = Integer.toBinaryString(m);
// System.out.println(word);
StringBuffer sb = new StringBuffer();
int len = 16 - word.length();
//補零
for(int j=0; j<len; j++){
sb.append("0");
}
sb.append(word);
sb.insert(0, "1110");
sb.insert(8, "10");
sb.insert(16, "10");
// System.out.println(sb.toString());
String s1 = sb.substring(0, 8);
String s2 = sb.substring(8, 16);
String s3 = sb.substring(16);
byte b0 = Integer.valueOf(s1, 2).byteValue();
byte b1 = Integer.valueOf(s2, 2).byteValue();
byte b2 = Integer.valueOf(s3, 2).byteValue();
byte[] bf = new byte[3];
bf[0] = b0;
fullByte[i*3] = bf[0];
bf[1] = b1;
fullByte[i*3+1] = bf[1];
bf[2] = b2;
fullByte[i*3+2] = bf[2];
}
return fullByte;
}
uj5u.com熱心網友回復:
直接把TextView.setText的編碼改成任何一個默認的都是亂碼,只是其他的顯示的不是黑色菱形方塊加問號了uj5u.com熱心網友回復:
InputStreamReader(new FileInputStream(in), "UTF-8");轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/45624.html
標籤:Android
上一篇:android 使用第三方瀏覽器喚醒app 喚醒多次后 接受<intent-filter> 的activity的oncreate方法 無法再次被喚起
