从android上的php文件中发布并获取json结果

从android上的php文件中发布并获取json结果,php,android,eclipse,methods,Php,Android,Eclipse,Methods,我是android的新手。我已经搜索了很多,找到了很多代码,但仍然有问题 我有一个简单的php,比如:(它有两个变量,比如q&number) 在将数据发布到此页面后,将以JSON格式显示结果 我希望在php页面上获得该输出,并在android上使用该值(我的意思是我希望在eclipse中的变量上使用该值) 我已检查此代码: public void postData() { // Create a new HttpClient and Post Header HttpClien

我是android的新手。我已经搜索了很多,找到了很多代码,但仍然有问题

我有一个简单的php,比如:(它有两个变量,比如
q
&
number

在将数据发布到此页面后,将以JSON格式显示结果

我希望在php页面上获得该输出,并在android上使用该值(我的意思是我希望在eclipse中的变量上使用该值)

我已检查此代码:

public void postData() {
     // Create a new HttpClient and Post Header
     HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
} 
public void postData(){
//创建一个新的HttpClient和Post头
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://www.yoursite.com/script.php");
试一试{
//添加您的数据
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“id”,“12345”);
添加(新的BasicNameValuePair(“stringdata”、“Hi”);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//执行HTTP Post请求
HttpResponse response=httpclient.execute(httppost);
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
}捕获(IOE异常){
//TODO自动生成的捕捉块
}
} 

但是我不能用这个获得输出。

您必须使用Json解析器。请查找处理对服务器的get/post请求的ServiceHandler

ServiceHandler.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class ServiceHandler {

    static InputStream is = null;
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client

            HttpParams paramsH = new BasicHttpParams();
            paramsH.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpClient httpClient = new DefaultHttpClient(paramsH);

            //DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            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, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error: " + e.toString());
        }

        return response;

    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.HttpVersion;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.utils.URLEncodedUtils;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.CoreProtocolPNames;
导入org.apache.http.params.HttpParams;
导入android.util.Log;
公共类ServiceHandler{
静态InputStream为空;
静态字符串响应=null;
公共最终静态int GET=1;
公共最终静态int POST=2;
公共服务处理程序(){
}
/*
*拨打服务电话
*@url-发出请求的url
*@method-http请求方法
* */
公共字符串makeServiceCall(字符串url,int方法){
返回此.makeServiceCall(url,方法,null);
}
/*
*拨打服务电话
*@url-发出请求的url
*@method-http请求方法
*@params-http请求参数
* */
公共字符串makeServiceCall(字符串url,int方法,
列表参数){
试一试{
//http客户端
HttpParams paramsH=新的BasicHttpParams();
setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
HttpClient HttpClient=新的默认HttpClient(paramsH);
//DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpEntity HttpEntity=null;
HttpResponse HttpResponse=null;
//检查http请求方法类型
if(方法==POST){
HttpPost HttpPost=新的HttpPost(url);
//添加post参数
如果(参数!=null){
setEntity(新的UrlEncodedFormEntity(参数));
}
httpResponse=httpClient.execute(httpPost);
}else if(方法==GET){
//将参数附加到url
如果(参数!=null){
String paramString=URLEncodedUtils
.格式(参数“utf-8”);
url+=“?”+参数字符串;
}
HttpGet HttpGet=新的HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
为“UTF-8”)、8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
response=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误:+e.toString());
}
返回响应;
}
}
在youractivity.java中,这样称呼它

String resulting_json = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
ServiceHandler jsonParser = new ServiceHandler();
String URL = "http://domain.tld/post.php";
resulting_json = jsonParser.makeServiceCall(URL, ServiceHandler.POST, params);
Toast.makeText(youractivity.this, resulting_json, Toast.LENGTH_LONG).show();
String结果_json=null;
List params=new ArrayList();
添加(新的BasicNameValuePair(“id”,“12345”);
添加(新的BasicNameValuePair(“stringdata”、“Hi”);
ServiceHandler jsonParser=新ServiceHandler();
字符串URL=”http://domain.tld/post.php";
生成的_json=jsonParser.makeServiceCall(URL,ServiceHandler.POST,params);
Toast.makeText(youractivity.this,resulted_json,Toast.LENGTH_LONG).show();

@IndraKumarS我说过。当我发送数据时,无法获取该页面的json输出。foce close:(你能发布你的json内容吗?json没有得到发送,我有两个字符串发送到那个页面,它返回一个json,那么如何在android中获得输出?如何测试?在设备中还是在模拟器中?…你是从php获得json数据?在设备上,也已经激活了用户许可。我在pc上从php获得json。
String resulting_json = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
ServiceHandler jsonParser = new ServiceHandler();
String URL = "http://domain.tld/post.php";
resulting_json = jsonParser.makeServiceCall(URL, ServiceHandler.POST, params);
Toast.makeText(youractivity.this, resulting_json, Toast.LENGTH_LONG).show();