使用不同的起始编号从 google 图片搜索 api 中获取 json 数据
getting json data from google image search api with different start numbers
google 图片搜索 url 看起来像这样 https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=eden%20hazard&rsz=8&start=4 其中每页最大图片中的 rsz 参数和起始参数是页码。我能够在页面中获取所有图像。但是对于说 20 页,即 start= 0 ... 19,我不知道这样做。我下面的代码显示了我是如何从页面中获取图像的。请让我知道如何让它获取多页图像。我尝试在我的异步任务(okhttp enqueue)之外使用 for 循环。
package com.paveynganpi.allsearch;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class ImageGrid extends ActionBarActivity {
private static final String TAG = ImageGrid.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_grid, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
protected GridView mGridView;//reference to gridview in fragment_image_grid.xml
protected int start = 0;//variable to change pages from google Api
//contains extra images urls to supply to ... when need
protected ArrayList<String> mBigImagesUrls;
//contains image urls to inject into gridview
protected static ArrayList<String> mSmalImagesUrls = new ArrayList<String>();
protected static String mEditedString;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_image_grid, container, false);
final ArrayList<String> testList = new ArrayList<String>();
//gets the edited string from MainActivity
Bundle args = getActivity().getIntent().getExtras();
mEditedString = args.getString("space");
String imagesUrl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ mEditedString +"&rsz=8&start=" + start;
//populate(start,imagesUrl.substring(0,imagesUrl.length()-1));
if(isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imagesUrl).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
}
});
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught :", e);
}
}
});
}
else{
Toast.makeText(getActivity(), "Network is unavailable", Toast.LENGTH_LONG).show();
}
return rootView;
}
//get data
private ArrayList<String> getCurrentDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject responseData = jsonObject.getJSONObject("responseData");
ArrayList<String> localList = new ArrayList<String>();
JSONArray results = responseData.getJSONArray("results");
for(int i =0;i<results.length(); i++){
localList.add(results.getJSONObject(i).getString("url"));
}
return localList;
}
//An AlertDialog to display to user when an error occurs
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getActivity().getFragmentManager(),"error_dialog");
}
//checks if user is connected to a network
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isAvailable = false;
if(activeNetwork != null && activeNetwork.isConnectedOrConnecting()){
isAvailable = true;
}
return isAvailable;
}
}
}
您可以创建如下方法:
public String getImagesForPage(int page){
return "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ mEditedString +"&rsz=8&start=" + page;
}
然后:
for (start=0;start<20;start++){
if(isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(getImagesForPage(start)).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
}
});
}
...
}
我建议您只使用连接逻辑创建一个方法。此代码将下载 20 页内容并在每次请求完成时更新您的 gridView。因此,最后,您将拥有包含最后一页内容的 gridView。要只存储页面的内容,请创建一个 HashMap<Integer,List<String>>
来存储每个页面的 url。
google 图片搜索 url 看起来像这样 https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=eden%20hazard&rsz=8&start=4 其中每页最大图片中的 rsz 参数和起始参数是页码。我能够在页面中获取所有图像。但是对于说 20 页,即 start= 0 ... 19,我不知道这样做。我下面的代码显示了我是如何从页面中获取图像的。请让我知道如何让它获取多页图像。我尝试在我的异步任务(okhttp enqueue)之外使用 for 循环。
package com.paveynganpi.allsearch;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class ImageGrid extends ActionBarActivity {
private static final String TAG = ImageGrid.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_grid, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
protected GridView mGridView;//reference to gridview in fragment_image_grid.xml
protected int start = 0;//variable to change pages from google Api
//contains extra images urls to supply to ... when need
protected ArrayList<String> mBigImagesUrls;
//contains image urls to inject into gridview
protected static ArrayList<String> mSmalImagesUrls = new ArrayList<String>();
protected static String mEditedString;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_image_grid, container, false);
final ArrayList<String> testList = new ArrayList<String>();
//gets the edited string from MainActivity
Bundle args = getActivity().getIntent().getExtras();
mEditedString = args.getString("space");
String imagesUrl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ mEditedString +"&rsz=8&start=" + start;
//populate(start,imagesUrl.substring(0,imagesUrl.length()-1));
if(isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imagesUrl).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
}
});
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught :", e);
}
}
});
}
else{
Toast.makeText(getActivity(), "Network is unavailable", Toast.LENGTH_LONG).show();
}
return rootView;
}
//get data
private ArrayList<String> getCurrentDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject responseData = jsonObject.getJSONObject("responseData");
ArrayList<String> localList = new ArrayList<String>();
JSONArray results = responseData.getJSONArray("results");
for(int i =0;i<results.length(); i++){
localList.add(results.getJSONObject(i).getString("url"));
}
return localList;
}
//An AlertDialog to display to user when an error occurs
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getActivity().getFragmentManager(),"error_dialog");
}
//checks if user is connected to a network
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isAvailable = false;
if(activeNetwork != null && activeNetwork.isConnectedOrConnecting()){
isAvailable = true;
}
return isAvailable;
}
}
}
您可以创建如下方法:
public String getImagesForPage(int page){
return "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ mEditedString +"&rsz=8&start=" + page;
}
然后:
for (start=0;start<20;start++){
if(isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(getImagesForPage(start)).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
}
});
}
...
}
我建议您只使用连接逻辑创建一个方法。此代码将下载 20 页内容并在每次请求完成时更新您的 gridView。因此,最后,您将拥有包含最后一页内容的 gridView。要只存储页面的内容,请创建一个 HashMap<Integer,List<String>>
来存储每个页面的 url。