Java通过HttpClient获取建议词

httpclient使用方法

1.http5导jar方式实现

  1. 下载HttpClient 5.0

  2. 根据需要导入jar包

    httpclient5-5.0.jar
    httpclient5-fluent-5.0.jar
    slf4j-api-1.7.25.jar
    httpcore5-5.0.jar

    当然全部导进去也没关系

代码实现

package ch11.netDemo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.fluent.Request;

public class HttpSuggestion extends JFrame {

	
	private static final long serialVersionUID = 1L;
	JTextField txtInput = new JTextField();
	JList<String> lstSuggestion = new JList<>();
	
	public static void main(String... args) throws Exception {
		SwingUtilities.invokeLater(() -> {
			new HttpSuggestion();
		});

	}
	
	public HttpSuggestion() {
		super("HttpClient获取建议词");
//		Container 是Component的子类,具有组件的所有性质,用来容纳其他组件和容器,在其可视区显示这些组件
//		默认为BorderLayout布局
		Container content = this.getContentPane();
		content.add(BorderLayout.NORTH, txtInput);
//		JList添加到滚动面板,并加入 content的中部
		content.add(BorderLayout.CENTER,new JScrollPane(lstSuggestion));
//		设置宽和高
		this.setSize(800, 560);
//		设置窗体居中
		this.setLocationRelativeTo(null);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
//		JTextField组件添加键盘事件
		txtInput.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				new Thread(() -> {
					try {
//						鼠标按下后,获取文本框字符串
						String word = txtInput.getText();
//						根据用户输入,到百度api获取建议词
						String[] suggestion = getAllSuggestion(word);
						
						SwingUtilities.invokeLater(() -> {
//							清空 JList列表
							lstSuggestion.removeAll();
//							显示建议词到JList
							lstSuggestion.setListData(suggestion);
//							更新界面
							lstSuggestion.updateUI();
						});
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}).start();
			}
		});
//		JList列表被选中事件,点击后添加到JTextField组件中
		lstSuggestion.addListSelectionListener(e -> {
			txtInput.setText(lstSuggestion.getSelectedValue());
		});
	}
	public static String[] getAllSuggestion(String word)
			throws UnsupportedEncodingException, ClientProtocolException,
			IOException {
		if (word == null || word.length() == 0)
			return new String[0];

		String url = "http://suggestion.baidu.com/su?wd="
				+ URLEncoder.encode(word, "utf-8");
		url += "&rnd=" + Math.random();
		String content =Request.get(url)
				.addHeader("cookie", "BDUSS=Aadasdfsfee")
				.execute()
				.returnContent().asString();

		System.out.println(content);
//		window.baidu.sug({q:"16",p:false,s:["163","16影视","1688阿里巴巴批发网","168","1688黄页网","16岁","1688","163黄页网站芭蕉影视","161725","1644年"]});
		String[] sug = content.replaceAll(".*,s:\\[([^\\]]*)\\].*", "$1")
				.replaceAll("\"", "").split(",");
		return sug;
	}

}

实现效果
在这里插入图片描述

2.直接引用maven依赖方式

这里使用的代码与上面有所不同,因为使用的版本和上面不一样,maven仓库还没有上面http5的依赖,这里只能使用http4相关依赖
主要依赖

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/fluent-hc -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

源码实现

package com.example.springjpa.test;

import org.apache.http.client.*;
import org.apache.http.client.fluent.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class HttpSuggestion2 extends JFrame {

    JTextField txtInput = new JTextField();
    JList<String> lstSuggestion = new JList<>();

    public HttpSuggestion2() {
        super("auto suggestion");
        getContentPane().add(BorderLayout.NORTH, txtInput);
        getContentPane().add(BorderLayout.CENTER,
                new JScrollPane(lstSuggestion));
        setSize(600, 500);
        this.setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        txtInput.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent arg0) {
                new Thread(() -> {
                    try {
                        String word = txtInput.getText();
                        String[] suggestion = fetchSuggestion(word);
                        SwingUtilities.invokeLater(() -> {
                            lstSuggestion.removeAll();
                            lstSuggestion.setListData(suggestion);
                            lstSuggestion.updateUI();
                        });
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }).start();
            }
        });

        lstSuggestion.addListSelectionListener(e -> {
            txtInput.setText(lstSuggestion.getSelectedValue());
        });
    }

    public static void main(String... args) throws Exception {
        // String word = "人";
        // fetchSuggestion(word);

        SwingUtilities.invokeLater(() -> {
            new HttpSuggestion2();
        });

    }

    public static String[] fetchSuggestion(String word)
            throws UnsupportedEncodingException, ClientProtocolException,
            IOException {
        if (word == null || word.length() == 0)
            return new String[0];

        String url = "http://suggestion.baidu.com/su?wd="
                + URLEncoder.encode(word, "utf-8");
        url += "&rnd=" + Math.random();

        String content = Request.Get(url)
                .addHeader("cookie", "BDUSS=Aadasdfsfee").execute()
                .returnContent().asString();

        System.out.println(content);
        // window.baidu.sug({q:"人",p:false,s:["人体艺术","人体艺术图片","人人网","人体艺术摄影","人民币对美元汇率","人体","人人贷","人人影视"]});

        String[] sug = content.replaceAll(".*,s:\\[([^\\]]*)\\].*", "$1")
                .replaceAll("\"", "").split(",");
        return sug;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值