java - 如何使用最佳方式检索 Json 文件

标签 java android json http networking

我想显示包含特定子字符串的视频标题,例如 videoName="apple":

因此,为了执行此任务,我编写了一段代码来检索 Json 文件并获取与该名称相关的所有条目:("https://gdata.youtube.com/feeds/api/videos?q= "+videoName+"&v=2&alt=json") 但不幸的是,我对此声明有异常(exception):

HttpResponse res = cli.execute(g);

这是我写的获取json文件的函数:

String GetUrlBody (String Url ){


            Log.d("s18", "ok");


            HttpClient cli = new DefaultHttpClient(); 

            Log.d("s19", "ok");


            HttpGet g = new HttpGet(Url); 

            Log.d("s20", "ok");


            try{

                Log.d("s21", "ok");

            HttpResponse res = cli.execute(g);

            Log.d("s22", "ok");


            if(res.getStatusLine().getStatusCode() == 200){

                Log.d("s23", "ok");


                String s =
            EntityUtils.toString(res.getEntity(), HTTP.UTF_8); 

                Log.d("s24", "ok");


                return s; 

            }else {

                Log.d("s25", "ok");

                return "Not Found"; 


            }




            }catch(Exception exx){

                Log.d("s26", "ok");

                Log.d("s27", exx.getMessage());



            }




            return null; 
        }

我所有的代码:

package com.example.task_10_vedioserach;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

public class MainActivity extends Activity {

    ListView vediolist;
    ImageButton search;
    Button history;
    EditText title;
    /////////////////
    ArrayList<String > vl; 
    ArrayAdapter< String > ad ; 
    ProgressDialog pd ; 
    /////////////////

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

        vediolist = (ListView) findViewById(R.id.vedioList);
        search = (ImageButton) findViewById(R.id.search);
        history = (Button) findViewById(R.id.history);
        title=(EditText) findViewById(R.id.vedioName);

        /////////////////////////////////////////////////////////////////

          vl = new ArrayList<String>(); 
          ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,vl); 

        //////////////////////////////////////////////////////////////
          Log.d("s0", "ok");

          search.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                final String vedioName=title.getText().toString();
                Log.d("s1", "ok");
                new conn().execute("https://gdata.youtube.com/feeds/api/videos?q="+vedioName+"&v=2&alt=json"); 
                Log.d("s2", "ok");
            }
        });

        pd = new ProgressDialog(this); 
        pd.setMessage("Wait Loading .... "); 
        pd.setCancelable(false); 
        vediolist.setAdapter(ad); 

    }



    class conn extends AsyncTask<String, Integer, String>{


        @Override
        protected void onPreExecute() {
            Log.d("s3", "ok");
             pd.show(); 
            super.onPreExecute();
            Log.d("s4", "ok");
        }
        @Override
        protected String doInBackground(String... arg0) {
            Log.d("s5", "ok");
            String s = GetUrlBody(arg0[0]); 
            Log.d("s6", "ok");
            return s;
        }

        @Override
        protected void onPostExecute(String result) {

            Log.d("s7", "ok");


        try{

            Log.d("s8", "ok");

            JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();

            Log.d("s9", "ok");


        JSONObject feed = jo.optJSONObject("feed");
        Log.d("s10", "ok");

        JSONArray ent = feed.optJSONArray("entry");
        Log.d("s11", "ok");



        for(int i = 0 ; i<ent.length() ; i++){

        String ti = ent.getJSONObject(i).
                getJSONObject("title").getString("$t");
        vl.add(ti); 


        }

        Log.d("s12", "ok");


        ad.notifyDataSetChanged();
        Log.d("s13", "ok");

        }catch(Exception exx) {
            Log.d("s14", "ok");

        }

        Log.d("s15", "ok");

            pd.dismiss(); 
            Log.d("s16", "ok");

            super.onPostExecute(result); 
            Log.d("s17", "ok");


        } 




        String GetUrlBody (String Url ){


            Log.d("s18", "ok");


            HttpClient cli = new DefaultHttpClient(); 

            Log.d("s19", "ok");


            HttpGet g = new HttpGet(Url); 

            Log.d("s20", "ok");


            try{

                Log.d("s21", "ok");

            HttpResponse res = cli.execute(g);

            Log.d("s22", "ok");


            if(res.getStatusLine().getStatusCode() == 200){

                Log.d("s23", "ok");


                String s =
            EntityUtils.toString(res.getEntity(), HTTP.UTF_8); 

                Log.d("s24", "ok");


                return s; 

            }else {

                Log.d("s25", "ok");

                return "Not Found"; 


            }




            }catch(Exception exx){

                Log.d("s26", "ok");

                Log.d("s27", exx.getMessage());



            }




            return null; 
        }



    }

这是完整的 Stacktrace: HERE

最佳答案

我个人会推荐使用像 GSON 和 Jackson 这样的东西。链接如下:

GSON: https://sites.google.com/site/gson/gson-user-guide http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ http://albertattard.blogspot.co.at/2009/06/practical-example-of-gson.html

jackson : http://jackson.codehaus.org/Tutorial http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

现在您必须了解使用这些工具不仅仅是“懒人”。它们是构建良好且快速的映射器。他们将比您在短时间内单独想到的任何算法/方法更快、更容易地完成工作。希望这对您有所帮助!

关于java - 如何使用最佳方式检索 Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17591303/

相关文章:

java - 在 Java 中绑定(bind) XML 文件的最佳方法 (NetBeans)

java - 从 JavaFX 2.0 中的 TableView 读取多项选择

javascript - node-red js 中的 HTTP POST

java - 从mysql行中获取数据并通过Java中的ResultSet分别显示

java - 如何为所有 Android 应用程序设置 Holo 灯光主题

c# - 将 android 模拟器连接到本地主机 web 服务 [C#]

javascript - 如何在Json Node js中传递变量的值而不是变量名

json - 从 JWT(JSON 网络 token )获取用户 ID

java - 无法弄清楚 java.lang.ArrayIndexOutOfBoundsException : length=1; index=1 is coming from 在哪里

android - 为什么我的 GridView 只显示一列?