我做了一些研究来解决我的问题,但遗憾的是直到现在我还不能。这没什么大不了的,但我一直坚持下去..
我需要在搜索引擎(例如 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 类,为此我只是扩展,我确定这是错误的,但我看到其他人这样做;这是第一个问题,我该怎么做?
第二个也是最重要的我收到语法错误:
我没有完全理解“connection.setRequestProperty("Accept-Charset", "UTF-8");"的含义和用途 '类(class)阅读我可以理解这是关于我的请求可能会出现的字符,但即使我不清楚语法错误
我对以下链接进行了研究:
- How to send HTTP request in java?
- getting text from password field
- http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
- 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/