从android中的localhost获取JSON对象

时间:2013-08-03 08:47:07

标签: android json

我需要从我的localhost获取数据。我的代码如下所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


 // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    String url = "http://10.0.2.2:8080/";

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        JSONArray value = json.getJSONArray("one");
        String output = value.toString();
        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(output);

        // Set the text view as the activity layout
        setContentView(textView);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}
public class JSONParser {

    InputStream is = null;
     JSONObject jObj = null;
     String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

然而我的应用程序在打开时崩溃了。有人可以帮我解决我的错误吗?为了您的信息,我通过使用web.py

运行python脚本来设置本地主机

Logcat错误如下:

08-03 08:55:47.093: E/AndroidRuntime(797): FATAL EXCEPTION: main
08-03 08:55:47.093: E/AndroidRuntime(797): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.customview/com.example.customview.MainActivity}: android.os.NetworkOnMainThreadException
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.os.Looper.loop(Looper.java:137)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.main(ActivityThread.java:5041)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.lang.reflect.Method.invokeNative(Native Method)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.lang.reflect.Method.invoke(Method.java:511)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-03 08:55:47.093: E/AndroidRuntime(797):  at dalvik.system.NativeStart.main(Native Method)
08-03 08:55:47.093: E/AndroidRuntime(797): Caused by: android.os.NetworkOnMainThreadException
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-03 08:55:47.093: E/AndroidRuntime(797):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-03 08:55:47.093: E/AndroidRuntime(797):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-03 08:55:47.093: E/AndroidRuntime(797):  at libcore.io.IoBridge.connect(IoBridge.java:112)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.net.Socket.connect(Socket.java:842)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.example.customview.MainActivity$JSONParser.getJSONFromUrl(MainActivity.java:75)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.example.customview.MainActivity.onCreate(MainActivity.java:36)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.Activity.performCreate(Activity.java:5104)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-03 08:55:47.093: E/AndroidRuntime(797):  ... 11 more

1 个答案:

答案 0 :(得分:0)

您正尝试在主线程/ UI线程上进行网络操作,这就是它提供RunTimeExceptionNetworkOnMainThreadException的原因。看看这一行

08-03 08:55:47.093: E/AndroidRuntime(797): Caused by: android.os.NetworkOnMainThreadException

在后台线程上进行网络操作,例如使用AsyncTask