【问题标题】:HTTP Request passing Keywords to searchHTTP 请求传递关键字进行搜索
【发布时间】:2013-06-21 18:34:04
【问题描述】:

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

我需要在 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 类并为此进行扩展,我确定这是错误的,但我看到其他人这样做;这是第一个问题,我该怎么做?

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

我没有完全理解 "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

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

编辑:[主题已解决]

【问题讨论】:

  • 请将语法错误报告为文本
  • 拳头把你的代码放在一些不在类中的方法中
  • @NullPointerException 这些语法问题,谢谢,我从现在开始对 java 不太熟悉,而且我仍然经常犯这些错误。但是我仍然缺少类之间的字符串传递部分......

标签: java string http httprequest urlconnection


【解决方案1】:

试试这个代码:(cmets inlined)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2021-08-23
    相关资源
    最近更新 更多