1

我一直在开发一个从服务器中提取一些 JSON 字符串的应用程序。要访问 JSON,我需要使用密钥和秘密进行发布。否则我会收到一条错误消息,提示缺少密钥和/或秘密。

我的 JSONfunctions.java

package com.spxc.ssa.streaming.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("key", "12345"));
                nameValuePairs.add(new BasicNameValuePair("secret", "AndDev is Cool!"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }


                //mhfgpammv9f94ddayh8GSweji

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

我的活动:

package com.spxc.ssa.streaming;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;

public class ListMoviesController extends SherlockListActivity implements
        OnClickListener {

    private ProgressDialog mDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.dblist);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Movies");

        JsonAsync asyncTask = new JsonAsync();
        // Using an anonymous interface to listen for objects when task
        // completes.
        asyncTask.setJsonListener(new JsonListener() {
            @Override
            public void onObjectReturn(JSONObject object) {
                handleJsonObject(object);
            }
        });
        // Show progress loader while accessing network, and start async task.
        mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
                getString(R.string.loading), true);
        asyncTask.execute("http://sirsmokealot.ch/api/video/movies/");

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            break;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    private void handleJsonObject(JSONObject object) {
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        try {

            JSONArray shows = object.getJSONArray("items");

            for (int i = 0; i < shows.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = shows.getJSONObject(i);

                map.put("video_id", String.valueOf(i));
                map.put("video_title", "" + e.getString("video_title"));
                map.put("video_channel", "" + e.getString("video_channel"));
                map.put("video_location", "" + e.getString("video_location"));
                mylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
                new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
                        R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv
                        .getItemAtPosition(position);

                Intent myIntent = new Intent(ListMoviesController.this,
                        TestVideoController.class);
                myIntent.putExtra("video_title", o.get("video_title"));
                myIntent.putExtra("video_channel", o.get("video_channel"));
                myIntent.putExtra("video_location", o.get("video_location"));
                startActivity(myIntent);
            }
        });

        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

}

我的日志猫说:

Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0 of 

任何帮助深表感谢!谢谢

4

1 回答 1

2

从服务器获得响应后,您错过了这两行

// 执行 HTTP Post 请求

 HttpResponse response = httpclient.execute(httppost);
 HttpEntity httpEntity = httpResponse.getEntity();
 is = httpEntity.getContent();
于 2013-03-13T08:54:25.690 回答