获取信息从JSON [英] Getting message from JSon

查看:210
本文介绍了获取信息从JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的code,以获得从一个文件PHP一个简单的消息,给我一个JSON对象,我有我的code没有错误和PHP code工作做好了,可以请你帮我找的是我的code事项:)

JAVA code:

 包com.example.httpclient;进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.TextView;公共类MainActivity延伸活动{    TextView的myListView;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        尝试{
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.activity_main);            //这是我们的TextView元素
            myListView =(的TextView)findViewById(R.id.textView1);            //让我们尝试连接
            尝试{
                //创建一个新的客户端对象
                HttpClient的HttpClient的=新DefaultHttpClient();                //现在张贴到您的演示网址
                HttpPost httppost =新HttpPost(http://goldengym.ma/test/test1.php);                //执行职务,并得到响应
                HTT presponse响应= httpclient.execute(httppost);                //从响应消息
                HttpEntity实体= response.getEntity();                //获取消息的内容
                InputStream的网= entity.getContent();                //响应转换成字符串
                尝试{
                    的BufferedReader读者=新的BufferedReader(新的InputStreamReader(纤维网,ISO-8859-1),8);                    //读取响应中的一个线
                    myListView.setText(reader.readLine());                    //慢我们的InputStream
                    webs.close();                }赶上(例外五){
                    Log.e(log_tag,错误转换结果+ e.toString());
                }
            }赶上(例外五){
                Log.e(log_tag,在HTTP连接错误+ e.toString());
            }
        }赶上(例外五){
            Log.e(log_tag,错误+ e.toString());
        }
    }}

还有就是PHP code:

 < PHP    $结果='TEST的工作,我们得到了连接;    打印json_en code($结果);?>

和有我logcat的:

 十二月3日至3日:35:02.918:I / ActivityManager(1995):强制停止包com.example.httpclient的uid = 10118十二月3日至3日:35:04.518:W /软件包管理系统(1995):为PKG code路线:从com.example.httpclient改变/data/app/com.example.httpclient-2.apk到/数据/应用/com.example.httpclient-1.apk十二月3日至3日:35:04.518:I / ActivityManager(1995):强制停止包com.example.httpclient的uid = 10118十二月3日至3日:35:04.518:W /软件包管理系统(1995):为PKG资源路径:从com.example.httpclient改变/data/app/com.example.httpclient-2.apk到/数据/应用/ COM。 example.httpclient-1.apk十二月3日至3日:35:05.218:I / ActivityManager(1995):强制停止包com.example.httpclient的uid = 10118十二月3日至3日:35:05.493:D / Launcher.LauncherModel(5871): - >包:com.example.httpclient十二月3日至3日:35:05.723:D / Launcher.LauncherModel(5871): - >更新包com.example.httpclient十二月3日至3日:35:05.723:D / Launcher.LauncherModel(5871): - >包:com.example.httpclient十二月3日至3日:35:05.913:V / BackupManagerService(1995):updatePackageParticipantsLocked:com.example.httpclient十二月3日至3日:35:06.188:D / PackageBroadcastService(2465):接收到的广播行动= android.intent.action.PACKAGE_REMOVED和URI = com.example.httpclient十二月3日至3日:35:06.523:V / BackupManagerService(1995):updatePackageParticipantsLocked:com.example.httpclient十二月3日至3日:35:07.598:W / DeepLinking(3458):没有深层链接安装数据发现com.example.httpclient十二月3日至3日:35:07.663:D / PackageBroadcastService(2465):接收到的广播行动= android.intent.action.PACKAGE_ADDED和URI = com.example.httpclient十二月3日至3日:35:07.703:D / PackageAddedReceiver(2234):包添加com.example.httpclient十二月3日至3日:35:08.048:D / PackageBroadcastService(2465):接收到的广播行动= android.intent.action.PACKAGE_REPLACED和URI = com.example.httpclient


解决方案

 包com.example.httpclient;进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口android.os.Build;
进口android.os.Bundle;
进口android.os.StrictMode;
进口android.annotation.TargetApi;
进口android.app.Activity;
进口android.util.Log;
进口android.view.Menu;
进口android.widget.TextView;
公共类MainActivity延伸活动{
    TextView的myListView;@TargetApi(Build.VERSION_ codeS.GINGERBREAD)
@覆盖
保护无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    //这是我们的TextView元素
    myListView =(的TextView)findViewById(R.id.tv);
    。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
    StrictMode.setThreadPolicy(政策);
    //让我们尝试连接
    尝试{
        //创建一个新的客户端对象
        HttpClient的HttpClient的=新DefaultHttpClient();        //现在张贴到您的演示网址
        HttpPost httppost =新HttpPost(http://10.0.2.2/testAndroid/test1.php);        //执行职务,并得到响应
        HTT presponse响应= httpclient.execute(httppost);        //从响应消息
        HttpEntity实体= response.getEntity();        //获取消息的内容
        InputStream的网= entity.getContent();        //响应转换成字符串
        尝试{
            的BufferedReader读者=新的BufferedReader(新的InputStreamReader(纤维网,ISO-8859-1),8);            //读取响应中的一个线
            myListView.setText(reader.readLine());            //慢我们的InputStream
            webs.close();        }赶上(例外五){
            Log.e(log_tag,错误转换结果+ e.toString());
        }
    }赶上(例外五){
        Log.e(log_tag,在HTTP连接错误+ e.toString());
    }
}
@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}}

PLZ试试这个code,这是工作的罚款。应该用

  StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建立()。
        StrictMode.setThreadPolicy(政策);

和Manifeast

 <?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.example.httpclient
    安卓版code =1
    机器人:=的versionName1.0>    <用途-SDK
        安卓的minSdkVersion =8
        机器人:targetSdkVersion =19/>    <使用许可权的android:NAME =android.permission.INTERNET对/>
    <使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/>
<应用
    机器人:allowBackup =真
    机器人:图标=@绘制/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
    <活动
        机器人:名字=com.provider.testdemo.MainActivity
        机器人:标签=@字符串/ APP_NAME>
        &所述;意图滤光器>
            <作用机器人:名字=android.intent.action.MAIN/>            <类机器人:名字=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;
< /用途>

I wrote the code below to get a simple message from a file php that send me a json object, I have no errors in my code and the PHP code work well, can you please help me to find what is the matter with my code :)

JAVA Code :

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());
        }
    }

}

And there is the PHP Code :

<?php

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

    print json_encode($result);

?>

And there is my 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

解决方案

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;
}

}

PLz try this code, It is working fine. There should use

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

and Manifeast

<?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>

这篇关于获取信息从JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆