2013-06-22 2 views
1

API 샘플 :빙 빙 API를이 예제 코드를 사용 코드

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

import org.apache.commons.codec.binary.Base64; 
import org.jsoup.Jsoup; 
public class bingSearch { 
    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     //--------------------------------------Bing search------------------------------ 
     String searchText = "swim"; 
     searchText = searchText.replaceAll(" ", "%20"); 
     String accountKey="Your-AccountKEY"; 
     byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); 
     String accountKeyEnc = new String(accountKeyBytes); 
     URL url; 
     try { 
      url = new URL( 
        "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc); 

    // conn.setRequestProperty("Accept", "application/json"); 

     BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream()))); 
     StringBuilder sb = new StringBuilder(); 
     String output; 
     System.out.println("Output from Server .... \n"); 
     char[] buffer = new char[4096]; 
     while ((output = br.readLine()) != null) { 
      sb.append(output); 

       // text.append(link + "\n\n\n");//Will print the google search links 
      //}  
     } 

     conn.disconnect(); 

     int find = sb.indexOf("<d:Description"); 

     int total = find + 1000; 

     System.out.println("Find index: " + find); 
     System.out.println("Total index: " + total); 
     sb.getChars(find+35, total, buffer, 0); 

     String str = new String(buffer); 

     int find2 = str.indexOf("</d:Description>"); 

     int total2 = find2 + 400; 
     System.out.println("Find index: " + find); 
     System.out.println("Total index: " + total); 
     char[] buffer2 = new char[1024]; 

     str.getChars(0, find2, buffer2 , 0); 
     String str2 = new String(buffer2); 
     str2 = Jsoup.parse(str2).text();  
     System.out.println(str2); 

     } catch (MalformedURLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    }   
} 

넣어 밖으로는 다음과 같습니다 서버에서

출력 ....

Find index: 1014 
Total index: 2014 
Find index: 1014 
Total index: 2014 
A computer is a general purpose device that can be programmed to carry out a finite set of arithmetic or logical operations. Since a sequence of operations can be ... 

그것은 단지 하나를 보여 결과, 그러나 나는 하나 이상의 결과가 필요합니다. 이 코드로 수행 할 수 있습니까? 아니면이 코드 대신 다른 것이 있습니까? 감사합니다

답변

1

당신은 결과를 Atom 피드로 요청하고 있습니다. 그 결과는 다시 돌아오고 있습니다. (특정 쿼리에 38785 자이기 때문에) 정말 Atom 피드로 처리하고 구문 분석해야합니다. 더 적절한 방법으로.

코드에서 하나의 결과 만 얻는 이유는 피드가 포함 된 sb 문자열을 반복하지 않는 것입니다. 이 방법으로 피드를 구문 분석하려면 conn.disconnect() 이후의 코드로 이동하여 sb.indexOf("<d:Description", int fromIndex)과 같은 문자열을 사용하여 새로운 일치 항목을 찾을 때마다 fromIndex가 증가하는 문자열을 트래버스해야합니다.

그러나 실제로는 Bing의 응답을 xml-feed처럼 처리해야하며 xml-library (예 : Rome)를 사용하여 구문 분석해야합니다.

+0

대답 주셔서 감사합니다. –

+0

@ NargesSadri 도움이되는 답변을 찾은 경우 자유롭게 upvote 및/또는 동의하십시오. – jpw

+0

답변 해 주셔서 감사합니다. 나는 자바와 라이브 라이브 검색으로 새로운입니다. 불행히도 나는 당신의 대답에 대해 많이 이해하지 못했습니다. 다른 빙 API 샘플 코드가 나를 위해 그것을합니까? 결과물에 하나 이상의 결과가 나오는 것을 의미합니까? –