AccessGoogle.java | (c) (ABA."Saba") |
package abagames.gglmekata; import java.io.*; import java.net.*; /** * Access Google with SOAP Interface. */ public class AccessGoogle { private final String DEFAULT_SERVICE_URL = "http://api.google.com/search/beta2"; private static String key; private static final String KEY_FILE_NAME = "google_key.cocoon.xml"; static { try { key = XMLHandler.getElement( XMLHandler.readFileString(GglMekataServlet.SYSTEM_ROOT_PATH+KEY_FILE_NAME), "key"); } catch ( IOException e ) { e.printStackTrace(); } } public static void setKey(String key) { AccessGoogle.key = key; } public static String getKey() { return key; } public String search(String query) throws MalformedURLException, IOException, UnsupportedEncodingException { URL url = new URL(DEFAULT_SERVICE_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); PrintWriter pst = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); pst.print("<?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"> <SOAP-ENV:Body> <ns1:doGoogleSearch xmlns:ns1=\"urn:GoogleSearch\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> <key xsi:type=\"xsd:string\">"); pst.print(key); pst.print("</key> <q xsi:type=\"xsd:string\">"); pst.print(query); pst.print("</q> <start xsi:type=\"xsd:int\">0</start> <maxResults xsi:type=\"xsd:int\">1</maxResults> <filter xsi:type=\"xsd:boolean\">true</filter> <restrict xsi:type=\"xsd:string\"></restrict> <safeSearch xsi:type=\"xsd:boolean\">false</safeSearch> <lr xsi:type=\"xsd:string\"></lr> <ie xsi:type=\"xsd:string\">utf8</ie> <oe xsi:type=\"xsd:string\">shift-jis</oe> </ns1:doGoogleSearch> </SOAP-ENV:Body> </SOAP-ENV:Envelope>"); pst.close(); conn.connect(); StringBuffer resultBuffer = new StringBuffer(); BufferedReader rsp = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for ( ; ; ) { String rspStr = rsp.readLine(); if ( rspStr == null ) break; resultBuffer.append(rspStr); } rsp.close(); return resultBuffer.toString(); } }