2013-06-21 60 views
1

我做了一些研究來解決我的問題,但可悲的是,直到現在我不能。這不是什麼大不了的,但我堅持下去。HTTP請求傳遞關鍵字搜索

我需要使用搜索引擎中的一些關鍵字進行搜索,例如谷歌。我這裏有兩個類來做到這一點:

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另一個類,我的商品價值,將一個字符串命名查詢。我需要將查詢傳遞給HttpRequest類,爲此我只是擴展,我確定它是錯誤的,但我看到有人正在做這個;這是第一個問題,我該怎麼做?

第二和我收到最重要的語法錯誤:

enter image description here enter image description here

我沒有完全理解的意義和效用「connection.setRequestProperty(」接收字符集「」 UTF-8 「);」 「當然,閱讀我能理解這是關於一個可能會拿出從我的請求,但即使語法錯誤並不清楚我

我在等環節做出研究caracters:

  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

他們都有一個很好的材料,但我不能完全理解它的一切,我試圖遵循的部分是行不通的。任何人都可以幫助我嗎?

編輯:[主題已解決]

+0

請報告語法錯誤文本 – Raedwald

+0

拳頭把你的代碼中的一些方法不 – NullPointerException

+0

類@ NullPointerException這些語法問題,謝謝,我從現在開始並不擅長java,對於我來說這些錯誤依然很常見。但我仍然錯過了類之間的字符串傳遞的一部分... –

回答

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