java - HTTP 请求传递要搜索的关键字

标签 java string http httprequest urlconnection

我做了一些研究来解决我的问题,但遗憾的是直到现在我还不能。这没什么大不了的,但我一直坚持下去..

我需要在搜索引擎(例如 google)中使用一些关键字进行搜索。我在这里有两个类(class)来做这个:

    package com.sh.st;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class EventSearch extends SearchScreen implements ActionListener {

    public EventSearch(){

        btsearch.addActionListener(this);

    }

        public void actionPerformed(ActionEvent e){

            if(e.getSource()==btsearch){
            String query=txtsearch.getText();
            }

        }



}

    package com.sh.st;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpRequest extends SearchScreen 
{
    URL url = new URL("google.com" + "?" + query).openConnection();
    URLConnection connection = url.openConnection();
    connection.setRequestProperty("Accept-Charset", "UTF-8"); //Possible Incompatibility
    InputStream response = connection.getInputStream();

}

因此,txtsearch 来自另一个名为 SearchScreen 的类,我将该值归因于一个名为 query 的字符串。我需要将查询传递给 HttpRequest 类,为此我只是扩展,我确定这是错误的,但我看到其他人这样做;这是第一个问题,我该怎么做?

第二个也是最重要的我收到语法错误:

enter image description here enter image description here

我没有完全理解“connection.setRequestProperty("Accept-Charset", "UTF-8");"的含义和用途 '类(class)阅读我可以理解这是关于我的请求可能会出现的字符,但即使我不清楚语法错误

我对以下链接进行了研究:

  1. How to send HTTP request in java?
  2. getting text from password field
  3. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  4. Using java.net.URLConnection to fire and handle HTTP requests

他们都有很好的 Material ,但我不能完全理解其中的所有内容,而且我试图遵循的部分不起作用。谁能帮帮我?

编辑:[主题已解决]

最佳答案

试试这个代码:(内联评论)

// Fixed search URL; drop openConnection() at the end
URL url = new URL("http://google.com/search?q=" + query);

// Setup connection properties (this doesn't open the connection)
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");

// Actually, open the HTTP connection
connection.connect();

// Setup a reader
BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));

// Read line by line
String line = null;
while ((line = reader.readLine()) != null) {
     System.out.println (line);
}

// Close connection
reader.close();

关于java - HTTP 请求传递要搜索的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242101/

相关文章:

java - 如何同时调用多个方法?

java - 返回 http 状态 404 的简单 Rest Web 服务

java - 使用来自 mockito-junit-jupiter 的 MockitoExtension 在构造函数测试类中进行空模拟

html - 我的服务器程序如何读取在 VB.NET 中使用 HTTP 'GET' 请求方法发送的变量?

php - 为什么传输前需要对图片进行base64编码?

java - 当没有剩余空间时,向 ArrayList 添加一个元素

c# - 找出两个字符串是否模糊的最快方法是什么? [不是另一个 Levenshtein 帖子]

C strcpy 和 char

Java TextField getText() 给我一个无法比较的字符串

http - URL 编码是/或否?