各位好,这是我在网上看到的一个输入框提示的程序,我改了一下,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 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();

});

}

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐