从JSon获取消息

时间:2014-03-03 12:18:57

标签: android

我编写了下面的代码,从一个文件php中获取一个简单的消息,发送给我一个json对象,我的代码中没有错误,PHP代码运行良好,请你帮我找到什么问题我的代码:)

JAVA代码:

package com.example.httpclient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

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 android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView myListView;

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

            //This is our textView element
            myListView = (TextView) findViewById(R.id.textView1);

            //Lets try to connect
            try{
                //Create a new client object
                HttpClient httpclient = new DefaultHttpClient();

                //Now post to your demo URL
                HttpPost httppost = new     HttpPost("http://goldengym.ma/test/test1.php");

                //Execute the post and get the response
                HttpResponse response = httpclient.execute(httppost);

                //Get the message from the response
                HttpEntity entity = response.getEntity();

                //Get the content of the message
                InputStream webs = entity.getContent();

                //Convert response to string
                try{
                    BufferedReader reader = new BufferedReader(new     InputStreamReader(webs, "iso-8859-1"), 8);

                    //Read one line of the response
                    myListView.setText(reader.readLine());

                    //Slow our inputStream
                    webs.close();

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

}

还有PHP代码:

<?php

    $result = 'TEST WORKED, WE GOT CONNECTION';

    print json_encode($result);

?>

还有我的logcat:

03-03 12:35:02.918: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118

03-03 12:35:04.518: W/PackageManager(1995): Code path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk

03-03 12:35:04.518: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118

03-03 12:35:04.518: W/PackageManager(1995): Resource path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk

03-03 12:35:05.218: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118

03-03 12:35:05.493: D/Launcher.LauncherModel(5871):   --> package:com.example.httpclient

03-03 12:35:05.723: D/Launcher.LauncherModel(5871):   --> update package com.example.httpclient

03-03 12:35:05.723: D/Launcher.LauncherModel(5871):   --> package:com.example.httpclient

03-03 12:35:05.913: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient

03-03 12:35:06.188: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REMOVED and uri=com.example.httpclient

03-03 12:35:06.523: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient

03-03 12:35:07.598: W/DeepLinking(3458): no deep link install data found for com.example.httpclient

03-03 12:35:07.663: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_ADDED and uri=com.example.httpclient

03-03 12:35:07.703: D/PackageAddedReceiver(2234): package added com.example.httpclient

03-03 12:35:08.048: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.httpclient

4 个答案:

答案 0 :(得分:0)

  1. 不允许在主线程上进行网络通话(http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
  2. 此外,您需要<uses-permission android:name="android.permission.INTERNET"/>文件中的AndroidManifest.xml
  3. 切勿使用Exception来处理您的例外情况。
  4. 此外,我会尽量避免将try-catch放入其他try-catch

答案 1 :(得分:0)

您无法在主线程上执行互联网操作。它会给你mainThreadException。 您必须使用Asynctask来执行这些操作。然后只能从Web服务中获取数据。

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

您可以使用此链接了解其工作原理。

答案 2 :(得分:0)

按如下方式进行:

public class MyAsyncTask extends AsyncTask<String, String, String> {
    private TextView myListView;

    public MyAsyncTask(TextView myListView){
       this.myListView = myListView;
    }
@Override
protected String doInBackground(String... params) {
         String response = null;
     HttpClient httpclient = new DefaultHttpClient();

            //Now post to your demo URL
            HttpPost httppost = new     HttpPost(params[0]);

            //Execute the post and get the response
            HttpResponse response = httpclient.execute(httppost);

            //Get the message from the response
            HttpEntity entity = response.getEntity();

            //Get the content of the message
            InputStream webs = entity.getContent();

            //Convert response to string
            try{
                BufferedReader reader = new BufferedReader(new     InputStreamReader(webs, "iso-8859-1"), 8);
                response = reader.readLine();
            }catch(Exception e){
                Log.e("log_tag", "Error converting result " +     e.toString());
            }finally{
                webs.close();
            }
       return response;
}

@Override
protected void onPostExecute(String result) {
    if(result != null){
            myListView.setText(result);
    }
}

您活动的onCreate()

new MyAsyncTask(myListView).execute("http://goldengym.ma/test/test1.php");

AsyncTask的关键方法是doInBackground(),它在单独的线程上执行冗长的操作,而onPostExecute在主线程上工作。有关详细信息,请参阅AsyncTask documentation。此外,在对服务器进行任何调用之前,您应该首先检查互联网是否可用。我没有在这里发布那个部分。希望这会有所帮助。

答案 3 :(得分:0)

package com.example.httpclient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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 android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;


public class MainActivity extends Activity {
    TextView myListView;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //This is our textView element
    myListView = (TextView) findViewById(R.id.tv);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);


    //Lets try to connect
    try{
        //Create a new client object
        HttpClient httpclient = new DefaultHttpClient();

        //Now post to your demo URL
        HttpPost httppost = new HttpPost("http://10.0.2.2/testAndroid/test1.php");

        //Execute the post and get the response
        HttpResponse response = httpclient.execute(httppost);

        //Get the message from the response
        HttpEntity entity = response.getEntity();

        //Get the content of the message
        InputStream webs = entity.getContent();

        //Convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);

            //Read one line of the response
            myListView.setText(reader.readLine());

            //Slow our inputStream
            webs.close();

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


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

请尝试使用此代码,工作正常。应该使用

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

和清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.httpclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET"/>  
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.provider.testdemo.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


</application>

相关问题