Android在解析JSON时,只解析了JSON数组的10项。在调试时,我发现 connection.openConnection() 之后的查询字符串; 返回空查询字符串,例如 http://www.example.com/recent_summary/?count=20如果我将计数减少到 5 并不重要,它仍然会返回 10 个项目。但是,当我浏览 browner 中的 URL 时。它返回所有 20 个项目..我认为我的代码有问题..服务器端工作正常还有一件事,当我在 android Studio 中检查 openConnection() 声明(URL.java)时,我发现很多红线..新手不知道它是否有帮助,但请帮助我。
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 ;
}
}
}
最佳答案
您的 url 似乎没有将所需的项目数正确地传送到服务器。如果您没有提供项目计数,10 应该是服务器配置为返回的默认项目计数。再次检查您的网址以查看其格式是否正确。
您提供的网址
http://www.example.com/recent_summary/?count=20
在“?”之前有一个“/”特点。可能是导致问题的原因。所以尝试像这样没有'/'字符的url
http://www.example.com/recent_summary?count=20
关于android - 在android中使用HttpUrlConnection查询字符串返回Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782385/