如何在android中使用JSON将数据发送到php页面

时间:2011-08-06 09:50:38

标签: android json

我正在尝试在我的网站和android之间进行通信,我很难将数据从我的android发送到php页面,我正在使用JSON进行通信,我怎么能这样做请帮助我........

1 个答案:

答案 0 :(得分:1)

为什么不实际从设备向php页面发出POST请求? PHP毕竟非常擅长处理请求,所以它不应该是一个问题。试试这个:

Java:

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yoursite.com");

try {
    // Add your data
    List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("string1", "foo"));
nameValuePairs.add(new BasicNameValuePair("string2", "bar"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

    //Check the response
    if( response == null ) return null;

    //POST DONE

} catch( Exception ex ) {

    ex.printStackTrace();

}

php:

<?php
    if( isset($_POST['string1']) ) {

        //Do stuff with the $_POST

    } else {

        //Nothing to see here

    }
?>