在Servlet中調用google的API

來源:互聯網
上載者:User

用google web API編程的步驟:
1)下載開發套件
  這個工具包中提供了文檔和調用Google web API服務的常式,常式有java和.net兩類,以及一個WSDL檔案以供在任何支援web服務的平台上編程之用。
2)建立一個google帳號
  為了訪問google Web API服務,你必須建立一個google帳號並取得授權碼。帳號和授權碼可使你一天內用程式查詢1000次。
我們要寫一個javabean來調用google的API
代碼如下:
package googleservlet;

import com.google.soap.search.*;

public class GoogleBean {

  private GoogleSearch search;
  private GoogleSearchResult googleRes;
  private final static String GOOGLE_KEY = "enxr3XRQertgf5l5ow/GyIE9TIwJQT/Uu";
 // 這個key是你重google申請的

  private String lineSep = "/n";

  //Settable bean properties
  private String query;  //存放查詢的關鍵字
  private boolean filter;
  private int maxResults;
  private int startRes;
  private boolean safeSearch;
  private String restrict;
  private String langRestrict;

  public GoogleBean(){

      query = "";
      restrict = "";
      langRestrict = "";

  }

  public String structureResult(GoogleSearchResult res){
     
    
      GoogleSearchResultElement[] elements = res.getResultElements(); //擷取查詢的結果,存放在數組裡
          String url ="";

          String results = "Estimated total results count: " +
              res.getEstimatedTotalResultsCount() + lineSep + lineSep;
          System.out.println(elements.length);
          
for (int i = 0; i < elements.length; i++){  //提取查詢的結果的URL

            url = elements[i].getURL();

            results += ("Title: " + elements[i].getTitle() + lineSep +
                    "URL: <a href="/blog//"";" + url + "/">" + url + "</a>"+ lineSep +
                        "Summary: " + elements[i].getSummary() + lineSep +
                        "Snippet: " + elements[i].getSnippet() + lineSep + lineSep);
          }

          return results;

 }

  public String getSearchResults() throws GoogleSearchFault {

      search = new GoogleSearch();

          search.setKey(GOOGLE_KEY);  //設定你的google key

          search.setFilter(filter); 

          if(restrict.length() > 0)
              search.setRestrict(restrict);

          search.setQueryString(query);  //設定查詢

          googleRes = search.doSearch();  //開始搜尋

          return structureResult(googleRes); 

  }

  public void setLineSep(String lineSep){

      this.lineSep=lineSep;
  }

   public String getLineSep(){

      return lineSep;
  }

  public void setQuery(String query){

      this.query = query;

  }

 public String getQuery(){

      return query;
  }

  public void setRestrict(String query){

      this.restrict = restrict;

  }

   public String getRestrict(){

      return restrict;
  }

  public void setLangRestrict(String query){

  this.langRestrict = langRestrict;

  }

  public String getLangRestrict(){

      return langRestrict;
  }

  public void setFilter(boolean filter){

      this.filter = filter;

  }

  public boolean getFilter(){

      return filter;
  }

   public void setSafeSearch(boolean filter){

      this.safeSearch = safeSearch;

  }

  public boolean getSafeSearch(){

      return safeSearch;
  }

  public void setMaxResults(int maxResults){

      this.maxResults = maxResults;

  }

  public int getMaxResults(){

      return maxResults;

  }

  public void setStartRes(int startRes){

      this.startRes = startRes;

  }

  public int getStartRes(){

      return startRes;

   }

   public void release(){

       search = null;
           googleRes = null;
   }

 

}

這個servlet為主查詢的介面和調用javabean

package googleservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;

public class GoogleServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {

        //set the MIME type of the response, "text/html"
    response.setContentType("text/html");

        //use a PrintWriter send text data to the client who has requested the servlet
    java.io.PrintWriter out = response.getWriter();

        //Begin assembling the HTML content
    out.println("<html><head>");

    out.println("<title>Initiate a Google Search</title></head><body>");
    out.println("<h2>Please enter your search terms</h2>");

    out.println(
        "<form method=/"POST/" action =/"" + request.getContextPath() +
            "/googleservlet/" target=/"window_name/" >");

    out.println("<table border=/"0/"><tr><td valign=/"top/">");
    out.println("Search terms: </td>  <td valign=/"top/">");
    out.println("<input type=/"text/" name=/"query/" size=/"15/">");
    out.println("</td></tr><tr><td valign=/"top/">");

        out.println("Restrict to Google sub-site... </td>  <td valign=/"top/">");
    out.println("<select name=/"restrict/"><option selected>none</option><option>unclesam</option><option>linux</option><option>mac</option><option>bsd</option></select>");
    out.println("</td></tr><tr><td valign=/"top/">");

    out.println("<input type=/"submit/" value=/"Submit Info/"></td></tr>");
    out.println("</table></form>");
    out.println("</body></html>");

    out.close();
     }

         public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,java.io.IOException{

        String query = request.getParameter("query");
        String restrict = request.getParameter("restrict");

        boolean isValid = (query == null || query.length() < 1) ? false : true;

    response.setContentType("text/html");

    java.io.PrintWriter out = response.getWriter();

    out.println("<html><head>");
    out.println("<title>Google results</title></head><body>");

        if (! isValid){
            out.println("<h2>Sorry, the query parameter was either empty or null</h2>");
        } else {

            out.println("<h2>Here are your search results</h2>");

                GoogleBean gb = new GoogleBean();
            gb.setFilter(true);

                gb.setLineSep("<br /><br />");

                if (restrict != null && restrict.length() > 0)
                    gb.setRestrict(restrict);

            gb.setQuery(query);

                try {
            out.println( gb.getSearchResults() );
                } catch (Exception e){

                    throw new ServletException( e.getMessage() );

                }

        }

        out.println("</body></html>");

    out.close();

        }

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.