在android中从服务器获取json数据时出错

时间:2016-02-09 22:54:33

标签: android json

我试图从服务器获取json数据,并且当前正在文本视图中显示该数据而不进行解析。问题是收到的数据总是为null但是当我访问json url时它会显示json数据。 当我使用http://api.androidhive.info/contacts/作为json url时,它正在运行。 但是,当我使用https://jsonblob.com/api/jsonBlob/56aa6129e4b01190df4c0b87作为json url时,它不是。我无法找到背后的原因。这很奇怪。我错过了什么?

这是我的MainActivity

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    ProgressDialog progressDialog;
    final int CONN_TIME = 1000 * 15;
    final String SERVER_ADDRESS = "http://api.androidhive.info/contacts/";

    TextView txtView;
    String ans;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtView = (TextView)findViewById(R.id.screen);

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Processing");
        progressDialog.setMessage("Please wait...");
        progressDialog.show();
        SyncUserDataAsyncTask s = new SyncUserDataAsyncTask();
        s.execute();
    }

    public class SyncUserDataAsyncTask extends AsyncTask<Void, Void,    JSONArray> {

    // User user;

        SyncUserDataAsyncTask() {

        }

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

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams,
                 CONN_TIME);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONN_TIME);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS);

            JSONArray returnedArray = null;
            try {

                HttpResponse httpResponse = client.execute(post);

                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                ans = result;
                JSONArray jArray = new JSONArray(result);
                if (jArray.length() == 0) {
                    returnedArray = null;
                } else {
                    returnedArray = jArray;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return returnedArray;
        }

        @Override
        protected void onPostExecute(JSONArray returnedArray) {
            progressDialog.dismiss();
            // callBack.done(returnedArray);
            //super.onPostExecute(returnedArray);
            txtView.setText(ans);
        }
    }

}

这里是mainactivity.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.co.MainActivity" >

    <TextView
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#E55A25" />

    <TextView
        android:id="@+id/screen"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/header"
        android:background="#acacac"
        android:textColor="#ffffff"
        android:text="hello,world" />
 </RelativeLayout>

2 个答案:

答案 0 :(得分:0)

您的问题是第一个链接有效,第二个链接没有,因为第一个链接是http链接,而第二个链接是https链接。代码进入catch块,异常是

javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

要解决此问题,请查看答案here

答案 1 :(得分:0)

作为一种解决方法,我建议您使用OkHttp库进行联网。您的异步任务将是这样的。

public class SyncUserDataAsyncTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(SERVER_ADDRESS)
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String response) {
        progressDialog.dismiss();
        txtView.setText(response);
    }
}

添加build.gradle

compile "com.squareup.okhttp3:okhttp:3.0.1"

我测试了两个网址并且工作正常