查询字符串在android中使用HttpUrlConnection返回Null

时间:2015-02-28 13:43:40

标签: android httpurlconnection

解析JSON时,在Android中

,它只解析10个JSON数组项。在调试时,我发现 connection.openConnection(); 之后的查询字符串返回null查询字符串,例如http://www.example.com/recent_summary/?count=20如果我将计数减少到5并不重要,它仍然返回10个项目。但是,当我浏览浏览器中的URL时。它返回所有20个项目..我的东西它我的代码有问题..服务器端工作正常和另外一件事,当我在Android工作室检查openConnection()声明(URL.java)我发现很多红线.. noob在这里知道它是否会有所帮助,但请帮助我。

public class MainListActivity extends ActionBarActivity {

protected  String TAG =  MainListActivity.class.getSimpleName(); 

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

    if(isNetworkAvailable()) {
        GetPostsTask getPostsTask = new GetPostsTask();
        getPostsTask.execute();

  }else
  {
      Toast.makeText(this,"No Network", Toast.LENGTH_SHORT).show();
  }

 }

private boolean isNetworkAvailable(){
ConnectivityManager manager =(ConnectivityManager)             getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false ;
    if (networkInfo != null && networkInfo.isConnected()){
    isAvailable = true ;
    }
   return isAvailable;
}


private class GetPostsTask extends AsyncTask<Object, Void, String>{


protected  String doInBackground(Object...arg){
        JSONObject jsonResponse ;
    try{
        URL url = new URL(http://www.example.com/recent_summary/?count=20 );
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.connect();

        int responseCode = connection.getResponseCode();
        Log.i("Response Code", ""+responseCode);

        InputStream inputStream = connection.getInputStream();
        Reader reader = new InputStreamReader(inputStream);
        BufferedReader r = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer();
        String line ;
        while((line=r.readLine()) != null){
            buffer.append(line + "\n");

        }

       Log.i("ResponseData" , ""+buffer);

        jsonResponse = new JSONObject(buffer.toString());
        JSONArray jsonPosts = jsonResponse.getJSONArray("posts") ;

        for(int i =0 ; i<jsonPosts.length() ; i++){
            JSONObject jsonPost = jsonPosts.getJSONObject(i);
            String title = jsonPost.getString("title");
            Log.i("Post"+i, title);

        }



    }catch (MalformedURLException ex){
        Log.i(TAG , "Error Found ", ex);
    }catch(IOException ex){
        Log.i(TAG , "Error Found ", ex);
    }catch (Exception ex){
        Log.i(TAG , "Error Found ", ex);
    }

    return null ;
}



  }
}

1 个答案:

答案 0 :(得分:1)

似乎您的网址没有正确地将所需的项目计数传达给服务器。如果您没有提供项目计数,则10应该是服务器配置为返回的默认项目计数。再次检查你的网址,看看它是否正确形成。

您提供的网址

http://www.example.com/recent_summary/?count=20

有&#39; /&#39;在&#39;之前?&#39;字符。可能是导致问题的原因。因此,请尝试不使用&#39; /&#39;像这样的人物

http://www.example.com/recent_summary?count=20