为什么我不能从网站读取下一页 json 数据到 json 缓冲区?

Why can't I read next page of json data from website into json buffer?

我正在做图书查找器 android 应用程序,它从电子书网站获取数据,每页显示 10 本书,当我按下下一步按钮时,它应该会显示接下来的 10 本书。

http://it-ebooks-api.info/v1/search/java&type=title

上面的 url 在 第一页 上给了我一个 json 书籍数组,它看起来像这样:

{"Error":"0","Time":0.0043,"Total":"327","Page":1,"Books":[{"ID":1542146786,"Title":"Java Phrasebook","Description":"Java Phrasebook gives you the code phrases............................... and so on

这个url - http://it-ebooks-api.info/v1/search/java&type=title&page=5

应该给我 第 5 页

的下一块 json 数据

我确实构建了有效的 url 但我的 httpUrlconnection 方法使用 GET 请求方法读取 总是只给我第一页 - 即使我形成 url第 5 页。

这是建立 URL 连接并从给定 URL:

存储到缓冲区的方法
private String MakeConnectionAndStoreBufferData(String validUrl){
HttpURLConnection urlConnection = null;
BufferedReader reader = null;


    URL url = new URL(validUrl); 
    // even if this url has &page=5 at the end
    // it still fetches data for page = 0

    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    InputStream inputStream = urlConnection.getInputStream();

    StringBuffer buffer = new StringBuffer();

    reader = new BufferedReader(new InputStreamReader(inputStream));

    String line;
    while((line = reader.readLine()) != null) {
        buffer.append(line + "\n");
    }

    return buffer.toString();

编辑:在拉米,我在这里展示了我如何实际构建我的 URL 地址 - 我在构建它们之后检查它们,它们看起来像预期的那样:

public class ProcessData extends AsyncTask<String, Void, String> {
private String createValidURL(String query, int page_counter) {
    Log.d(LOG_TAG, "create Valid url......");

    String BASE_URL = "http://it-ebooks-api.info/v1/search";

    String resultUrl = null ;
    if (page_counter == 0){

        destinationURL = Uri.parse(BASE_URL).buildUpon()
                .appendPath(query)
                .appendQueryParameter("type", "title")
                .build();

    resultUrl = destinationURL.toString();


}
   else if(page_counter > 0){

        destinationURL = Uri.parse(BASE_URL).buildUpon()
                .appendPath(query)
                .appendQueryParameter( "type", "title")
                .appendQueryParameter("page",  Integer.toString(page_counter) )
                .build();

        resultUrl = destinationURL.toString();

    }
    Log.d(LOG_TAG, "before we return url, it is :" + resultUrl);
    return resultUrl ;
}


public String doInBackground(String ...params) {

    String validUrl = createValidURL(params[0], 5);//5 is page counter        
    String result_buffer = MakeConnectionAndStoreBufferData(validUrl);
    return result_buffer ;
    }
    }

这是 mainactivity.java,我确实在搜索标题为 "java" 的书籍:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    // create valid URL, connect to it-ebooks website, read buffer, parse buffer to return complete list of books

    ProcessData data = new ProcessData();
    data.execute("java");//this calls doInBackground in processData class!
    }
http://it-ebooks-api.info/v1/search/java?type=title&page=5

经过仔细观察,我发现了错误——大约是?字后签名 java.

基本上你可以写....java?type=title&pa,它仍然会加载第一页!该网站是 "forgiving",默认情况下 return 第一页 如果查询格式不正确 - 如果页面丢失、不完整等

我找不到其他方法了!唯一的问题是 java ? -问号, 无论如何,这里没有人能帮助我,我很高兴我自己发现了这个错误!

我应该确保我的 url 已经更换了吗?用 &.

p.s。创建 urls 时要小心:追加查询参数可能会使 URL.

几乎正确

你的MainActivity.java

public class MainActivity extends ActionBarActivity {

Button btnPrev, btnNext;
static int page = 1;
TextView txtview;

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

    btnPrev = (Button) findViewById(R.id.previous);
    btnNext = (Button) findViewById(R.id.next);
    txtview = (TextView) findViewById(R.id.txtview);

    callServer(page);
    btnPrev.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (page > 1) {
                page = page - 1;
                callServer(page);
            }
        }
    });
    btnNext.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            page = page + 1;
            callServer(page);
        }
    });
}

protected void callServer(int pageNumber) {
    new ParserClass(MainActivity.this, new CalbackListener() {

        @Override
        public void onSuccess(JSONObject result) {
            try {
                String pageNo = result.getString("Page");
                txtview.setText("Page No : " + pageNo);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, page).execute();
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.soapsample.MainActivity" >

<TextView
            android:id="@+id/txtview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="@string/hello_world" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="20dp"
    android:orientation="horizontal"
    android:weightSum="2" >

    <Button
        android:id="@+id/previous"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Previous" />

    <Button
        android:id="@+id/next"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_below="@+id/previous"
        android:text="Next" />
</LinearLayout>

</RelativeLayout>

JsonParser.java class

public class ParserClass extends AsyncTask<Void, Void, JSONObject> {

private ProgressDialog dialog;

public interface CalbackListener {
    public void onSuccess(JSONObject result);
}

private int page;
private CalbackListener callback;
private String url = "http://it-ebooks-api.info/v1/search/java&type=title&page=";
private Context context;

public ParserClass(Context context, CalbackListener callback1, int page) {
    this.callback = callback1;
    this.page = page;
    this.context = context;
    this.url += String.valueOf(this.page);
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = ProgressDialog.show(context, "Title", "Loading...", true);
}

@Override
protected JSONObject doInBackground(Void... params) {

    String result = null;

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        Log.i("url", url);
        HttpResponse httpResponse = null;
        if (httpGet != null) {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            Log.i("Result", result);
        }
        return new JSONObject(result);
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

@Override
protected void onPostExecute(JSONObject result) {
    super.onPostExecute(result);
    dialog.dismiss();
    callback.onSuccess(result);
}
}