各位好,这是我在网上看到的一个输入框提示的程序,我改了一下,content
总是乱码,哪里的编码出问题了呢?我试着把content装成bytes[]在转成string还是乱码。
package com.bobliao;
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import org.apache.http.client.ClientProtocolException;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
public class SuggestionTest extends JFrame {
private JTextField textInput=new JTextField();
private JList<String> listSuggestions=new JList<>();
public SuggestionTest() {
super("SuggestionTest");
getContentPane().add(BorderLayout.NORTH,textInput);
getContentPane().add(BorderLayout.CENTER,
new JScrollPane(listSuggestions));
setSize(300,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
this.textInput.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e){
new Thread(() -> {
try{
String word=textInput.getText();
//word打印出来
System.out.println(word);
String[] suggestions=fetchSuggestionsFromBaidu(word);
SwingUtilities.invokeLater(() -> {
listSuggestions.removeAll();
listSuggestions.setListData(suggestions);
listSuggestions.updateUI();
});
}
catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}).start();
}
public String[] fetchSuggestionsFromBaidu(String word) throws
UnsupportedEncodingException,
ClientProtocolException,
IOException {
//获取建议词
String url="http://suggestion.baidu.com/su?wd="+URLEncoder.encode(word, "utf8");
URL urlReal=new URL(url);
InputStream stream=urlReal.openStream();
BufferedReader streamReader=new BufferedReader(new InputStreamReader(stream,"utf-8"));
StringBuffer stringBuffer=new StringBuffer();
String temp=null;
while((temp=streamReader.readLine())!=null){
stringBuffer.append(temp);
}
/*
* 这里的content总是会乱码啊*/
String content=new String(stringBuffer.toString());
System.out.println(content);
String[] suggestions=content.replaceAll(".*\\[(.*)\\].*", "$1").replaceAll("\"","").split(",");
return suggestions;
}
});
this.listSuggestions.addListSelectionListener(e -> {
textInput.setText(listSuggestions.getSelectedValue());
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() ->{
new SuggestionTest();
});
}
}
两个utf-8换成GBK
