HTTP请求将关键字传递给搜索

时间:2013-06-21 18:34:04

标签: java string http httprequest urlconnection

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

我需要在Google等搜索引擎中搜索一些关键字。我在这里有两节课来做这件事:

    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“)的含义和用途;” “课程阅读我可以理解这是关于可能会出现在我的请求中的字符,但即使语法错误对我来说还不清楚

我在以下链接中进行了研究:

  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
  5. 所有这些材料都有很好的材料,但是我无法完全理解它上面的所有内容,而我想要遵循的那部分是不起作用的。有人可以帮我吗?

    编辑:[解决主题]

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:(内联评论)

// 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();