代码如下,很简单,只是向服务器发送请求,得到一个XML流然后解析。。使用代理是因为公司限制的原因。
package com.searchWord;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* @author shuai.yang
*
*/
public class SearchWord extends JFrame. implements ActionListener {
/**
* default ID create by Eclipse
*/
private static final long serialVersionUID = -7624995201710742391L;
private static final String searchURL = "http://dict.cn/ws.php?q=";
private static final String errorMsg_NoFound = "No found";
private static final String sampleTitle = "sample:";
private static final String proxyURL = "gzcpx1001.gdnchina.com";
private static final String formTitle = "SFA中英文查询器-测试版本V1.0";
private static final String alertMsg = "请输入要查询的内容!";
private JTextArea r = new JTextArea(15, 26);
private JButton b = new JButton();
private JTextField t = new JTextField();
private JTextField proxyTxt = new JTextField();
private JCheckBox proxyCBox = new JCheckBox();
/**
* default construct
*
*/
public SearchWord() {
initForm();
}
/**
* init JFrame
*
*/
private void initForm() {
this.add(initPanel());
this.setTitle(formTitle);
this.setSize(350, 400);
Toolkit t = Toolkit.getDefaultToolkit();
this.setLocation(
(int) (t.getScreenSize().getWidth() - this.getWidth()) / 2,
(int) (t.getScreenSize().getHeight() - this.getHeight()) / 2);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
/**
* initPanel
*
* @return JPanel
*/
private JPanel initPanel() {
JPanel p = new JPanel();
JPanel pInput = new JPanel();
JPanel copyRight = new JPanel();
pInput.add(initText(), BorderLayout.CENTER);
pInput.add(initButton(), BorderLayout.CENTER);
JScrollPane pResult = new JScrollPane(initResultPanel(""));
copyRight.add(initProxyTxt(),BorderLayout.CENTER);
copyRight.add(initProxyCheckBox(),BorderLayout.CENTER);
p.add(pInput, BorderLayout.NORTH);
p.add(pResult, BorderLayout.CENTER);
p.add(copyRight, BorderLayout.CENTER);
return p;
}
/**
* initProxyCheckBox
*
* @return
*/
private JCheckBox initProxyCheckBox() {
proxyCBox.setText("使用代理");
proxyCBox.setSelected(true);
proxyCBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
proxyTxt.setEditable(false);
if (e.getStateChange() == ItemEvent.DESELECTED)
proxyTxt.setEditable(true);
}});
return proxyCBox;
}
/**
* initProxyTxt
*
* @return
*/
private JTextField initProxyTxt() {
proxyTxt.setColumns(18);
proxyTxt.setText(proxyURL);
proxyTxt.setEditable(false);
return proxyTxt;
}
/**
* initButton
*
* @return JButton
*/
private JButton initButton() {
b.setText("查询");
b.addActionListener(this);
return b;
}
/**
* initText for input
*
* @return JTextField
*/
private JTextField initText() {
t.setColumns(20);
t.addKeyListener(new KeyAdapter(){//添加直接回车查询事件
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 10){
actionPerformed(null);
}
}
});
return t;
}
/**
* initResultPanel for display result
*
* @param result
* @return JTextArea
*/
private JTextArea initResultPanel(String result) {
r.setAutoscrolls(true);
r.setText(result);
r.setEditable(false);
r.setLineWrap(true);
return r;
}
/**
* JButtion click
*/
public void actionPerformed(ActionEvent arg0) {
if ("".equals(t.getText().trim())) {
JOptionPane.showMessageDialog(this, alertMsg);
} else {
this.setTitle(formTitle);
initResultPanel(getSearchResult());
}
}
/**
* getSearchResult
*
* @return searchResult
*/
private String getSearchResult() {
StringBuffer result = new StringBuffer();
try {
// FileInputStream in = new FileInputStream(new File("d:/a.xml"));
InputStream in = getURLInputSteam(searchURL + t.getText().replaceAll(" ",""));
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(in);
NodeList nl = doc.getElementsByTagName("dict");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
if(null == e.getElementsByTagName("def").item(0).getFirstChild()){
result.append(errorMsg_NoFound).append("\n");
}else{
String explainDef = e.getElementsByTagName("def").item(0).getFirstChild().getNodeValue();
result.append(explainDef).append("\n");
NodeList nlSample = doc.getElementsByTagName("sent");
for (int j = 0; j < nlSample.getLength(); j++) {
if (j == 0) result.append("\n"+ sampleTitle + "\n");
String sample1 = e.getElementsByTagName("orig").item(j).getFirstChild().getNodeValue();
String sample2 = e.getElementsByTagName("trans").item(j).getFirstChild().getNodeValue();
result.append(sample1).append("\n").append(sample2).append("\n\n");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
/**
* getReslutString
* @param sb input String
* @param patternStr expression
* @param paramStart substring funtion used start number
* @param paramEnd substring funtion used end number
* @param nextRex judge whether need to do ( if it's chinese string)
* @return
* @throws UnsupportedEncodingException
*/
public static String getReslutString(String sb,String patternStr,int paramStart,int paramEnd,boolean nextRex) throws UnsupportedEncodingException{
StringBuffer result = new StringBuffer();
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher(sb);
int n = 0;
while (m.find()) {
String eachResult = "";
n++;
int start = m.start() + paramStart;
int end = m.end() - paramEnd;
if(nextRex){
String[] chineseStr = sb.split("<br>");
for(int i=0;i<chineseStr.length-1;i++){
eachResult = new String(chineseStr[i].getBytes("ISO-8859-1"),"GBK");
result.append(eachResult + "\n");
}
}else{
eachResult = sb.substring(start, end);
result.append(eachResult + "\n");
}
}
return result.toString();
}
/**
* getURL
*
* @param u
* @return getURL
*/
private InputStream getURLInputSteam(String u) {
URL url;//
InputStream is;//
try {
if (proxyCBox.isSelected() && !"".equals(proxyTxt.getText())) {
InetSocketAddress address = new InetSocketAddress(proxyURL, 8080);// 设置代理服务器
Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
url = new URL(u);
URLConnection conn = url.openConnection(proxy);
is = conn.getInputStream();
return is;
} else {// 不使用代理
url = new URL(u);
is = url.openStream();
return is;
}
} catch (MalformedURLException e) {
this.setTitle("必须是有效的URL地址!");
return null;
} catch (IOException e) {
this.setTitle("连接出错!");
return null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new SearchWord();
}
}