Android调用页面返回JSON错误

时间:2014-01-24 19:31:38

标签: java android

我有一个aspx页面,我从我的Android应用程序调用返回JSON文本,但下面的Java代码在这里打破BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

出现此错误。

错误 android.os.NetworkOnMainThreadException

你能帮助plesae吗?感谢

default.aspx return json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";

        //Write the message
        Response.Write("{'testvar':'testtext'}");
        //End the response causing it to be sent
        Response.End();
    }
}

android java

   public void connectWCF() {

        try {
            URL json = new URL("http://localhost:50851/Default.aspx");

            URLConnection jc = json.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

            String line = reader.readLine();

            reader.close();

        } catch(Exception e){

        }

链接我从中获取代码的想法 http://wyousuf.wordpress.com/2012/03/01/android-with-wcf-services/ http://matijabozicevic.com/blog/android-development/android-with-wcf-service

2 个答案:

答案 0 :(得分:1)

您正在主线程上进行网络通信。你应该使用AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html 

这是一个很好的视频,解释了使用AsyncTask的JSON解析。

http://www.youtube.com/watch?v=qcotbMLjlA4 

仅限测试,您可以在主要活动中添加以下内容,但这是不好的做法。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

答案 1 :(得分:1)

从android 3.0开始,你不能在主线程(换句话说,活动的任何部分)中对网页或类似的外部资源进行任何调用,除非你使用AsyncTask进行,以避免应用程序看起来等待来自外部数据源的响应时“锁定”并且无响应。因此,您需要使用和AsyncTask实现webservice调用。

AsyncTask的示例类:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;




public class cargaDatosRest extends AsyncTask<Context, Void, Void> {


    private Context c;
    private boolean resul = false;
    private String control = "";
    private String respStrS = "";

    public cargaDatosRest(Context C)
    {
        c = C;      
    }

    public String getStr()
    {
        return respStrS;
    }

    public String getControl()
    {
        return control;
    }

    @Override
    protected void onPreExecute() {     
        super.onPreExecute();
        //mProgressDialog.show();
    }

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

        HttpClient httpClient = new DefaultHttpClient();   

        HttpGet get = new HttpGet("url");                
        HttpResponse resp;

        get.setHeader("content-type", "application/json");

        try
        {

                        /*resp contains the response from the webService. respStr and respJSON allows to read that resp in JSON format. Just delete them if you don't need them. You can asign the values returned by the webservice to local variables in the AsyncTask class and then read them with public methods, like the resul variable.*/

                resp = httpClient.execute(getUsuarios);
            String respStr = EntityUtils.toString(resp.getEntity());

            JSONArray respJSON = new JSONArray(respStr);    

            this.resul = true;
        }
        catch(Exception ex)
        {           
            Log.e("ServicioRest","Error!", ex);
            this.resul = false;
        }           

    }           
    public boolean getResul()
    {
        return this.resul;
    }

    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(Void unused) {
        //mProgressDialog.dismiss();
    }   
}

//从活动中调用AsyncTask:

        CargaDatosRest CallRest = new CargaDatosRest(this.getApplicationContext());
        CallRest.execute();                     
        Log.v("WebService", "Just trying "+arest.getResul());