Bing Search API在Android中未返回结果

时间:2019-02-20 20:56:36

标签: java android azure bing-api

我最近试图在一个测试的Android Studio项目中实现以下代码,但我不知道为什么我不起作用。我什至无法输出有用的错误消息,可能会提示我找出问题所在。在这里,我包括了AsyncTask类,MainActivity和我用来解析数据的辅助类。任何帮助将不胜感激。

主要活动

public class MainActivity extends AppCompatActivity {

    // Enter a valid subscription key.
    static String subscriptionKey = "######################";

    static String host = "https://api.cognitive.microsoft.com";
    static String path = "/bing/v7.0/videos/search";
    static String searchTerm = "dog";
    static BingSearchResults.Result[] searchResults;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BingSearchTask.Callback callback = new BingSearchTask.Callback() {
            @Override
            public void onComplete(Object o, Error error) {
                BingSearchResults results = (BingSearchResults) o;

                searchResults = results.d.results;
            }
        };

        new BingSearchTask(searchTerm, 1, callback);
    }
}

异步任务类别

public class BingSearchTask extends AsyncTask<Void, Void, Void> {

    private final String TAG = getClass().getName();

    private String mSearchStr;
    private int mNumOfResults = 0;

    private Callback mCallback;
    private BingSearchResults mBingSearchResults;
    private Error mError;

    public BingSearchTask(String searchStr, int numOfResults, Callback callback) {
        mSearchStr = searchStr;
        mNumOfResults = numOfResults;
        mCallback = callback;
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            String searchStr = URLEncoder.encode(mSearchStr);
            String numOfResultsStr = mNumOfResults <= 0 ? "" : "&$top=" + mNumOfResults;
            String bingUrl = "https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27" + searchStr + "%27" + numOfResultsStr + "&$format=json";
            String accountKey = "######################";

            Log.d("here", "here");

            byte[] accountAccess = ("accountKey:" + accountKey).getBytes();
            byte[] accountKeyBytes = Base64.encode(accountAccess, Base64.DEFAULT);

            String accountKeyEnc = new String(accountKeyBytes);

            URL url = null;
            url = new URL(bingUrl);

            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
            InputStream response = urlConnection.getInputStream();
            String res = readStream(response);

            Gson gson = (new GsonBuilder()).create();
            mBingSearchResults = gson.fromJson(res, BingSearchResults.class);

            Log.d(TAG, res);
            //conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
            mError = new Error(e.getMessage(), e);
            Log.e("BingSearchTask", e.getMessage());
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if (mCallback != null) {
            mCallback.onComplete(mBingSearchResults, mError);
        }

    }

    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                //System.out.println(line);
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();


    }

    public interface Callback {
        void onComplete(Object o, Error error);
    }
}

帮助类

public class BingSearchResults {

    public ResultsContent d;

    public static class ResultsContent {
        public Result[] results;
        public String __next;
    }

    public static class Result {
        public String ID;
        public String Title;
        public String Description;
        public String DisplayUrl;
        public String Url;
        public Metadata __metadata;

    }

    public static class Metadata {
        public String uri;
        public String type;
    }

    public Result[] getResults(){
        if (d == null)
            return null;
        return d.results;
    }

    public String getNextUrl(){
        if (d == null)
            return null;
        return d.__next;
    }

    public boolean isEmpty(){
        return (d == null || d.results == null || d.results.length == 0);
    }

    public int size(){
        if (d == null || d.results == null)
            return 0;
        return d.results.length;
    }
}

1 个答案:

答案 0 :(得分:0)

如其他人所建议,请尝试首先在Postman中访问API。请注意,SubscriptionKey位于“标题”选项卡中,其名称为“ Ocp-Apim-Subscription-Key”

enter image description here