简体   繁体   English

如何使用POST方法从Android获取php的Json DATA?

[英]How to get Json DATA with php from Android using POST method?

I am trying to communication with php server and android 我正在尝试与php服务器和android通信

Here is my JAVA file and php 这是我的JAVA文件和php

// convert data into Json using gson library. //使用gson库将数据转换为Json。 -> it's fine! ->很好!

   String str = new TOJSON().tojson("testName", "TestPW", "testEmail", 77);

   USERDATA userdata = gson.fromJson(new HTTPCONNECTION().httpPost("http://testsever.com/test.php", str).toString(), USERDATA.class);

   textView textView = (TextView)findViewById(R.id.textView1);
   textView.setText(userdata.getName());

// to connect php server //连接php服务器

public class HTTPCONNECTION {


    public String httpPost(String url, String str){
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 30000);
        HttpResponse response;


        try {
            HttpPost httppost = new HttpPost(url);
            StringEntity entity = new StringEntity(str, "UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);

            HttpResponse httpResponse = client.execute(httppost); 
            HttpEntity httpEntity = httpResponse.getEntity();
            Log.v("OWL", EntityUtils.toString(httpEntity));

            return EntityUtils.toString(httpEntity);
        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } 
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }
}

and php file get json data and send json data to test 和php文件获取json数据并发送json数据进行测试

$value = json_decode(stripslashes($_POST), true);
echo (json_encode($value));

In my case on side PHP i use 就我而言,我使用PHP

 $_POST = json_decode(file_get_contents("php://input"));

And on Android side 在Android方面

StringEntity se = new StringEntity(jsonObject.toString(),
                    HTTP.UTF_8);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
request.setEntity(se);

PHP Manual - Input/Output PHP Streams PHP手册- 输入/输出PHP流

Full source of function sending POST JSON data to server from Android 从Android向服务器发送POST JSON数据的完整功能源

public static void restApiJsonPOSTRequest(
            final DefaultHttpClient httpclient, final HttpPost request,
            final JSONObject jsonObject, final Handler responder,
            final int responseCode, final int packetSize) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    try {

                        StringEntity se = new StringEntity(jsonObject
                                .toString(), HTTP.UTF_8);
                        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                                "application/json"));
                        request.setEntity(se);

                        HttpResponse response = httpclient.execute(request);
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            DataInputStream dis = new DataInputStream(entity
                                    .getContent());
                            byte[] buffer = new byte[packetSize];// In bytes
                            int realyReaded;
                            double contentSize = entity.getContentLength();
                            double readed = 0L;
                            while ((realyReaded = dis.read(buffer)) > -1) {
                                baos.write(buffer, 0, realyReaded);
                                readed += realyReaded;
                                sendDownloadingMessage(responder,
                                        (double) contentSize, readed);
                            }
                            sendCompleteMessage(responder,
                                    new InternetResponse(baos, responseCode,
                                            request.getURI().toString()));
                        } else {
                            sendErrorMessage(responseCode, responder,
                                    new Exception("Null"), request.getURI()
                                            .toString());
                        }
                    } catch (ClientProtocolException e) {
                        sendErrorMessage(responseCode, responder, e, request
                                .getURI().toString());
                    } catch (IOException e) {
                        sendErrorMessage(responseCode, responder, e, request
                                .getURI().toString());
                    } finally {
                        httpclient.getConnectionManager().shutdown();
                    }
                } catch (NullPointerException ex) {
                    sendErrorMessage(responseCode, responder, ex, request
                            .getURI().toString());
                }
            }
        }).start();
    }

or different way 或不同的方式

public static void postJSONObject(final String url,
            final Handler responder, final int responseCode,
            final int packetSize, final JSONObject jsonObject,
            final URLConnection connection) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(connection);
                sendConnectingMessage(responder);
                PrintWriter writer = null;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {

                    HttpURLConnection htt = (HttpURLConnection) connection;
                    htt.setRequestMethod("POST");
                    OutputStream output = connection.getOutputStream(); // exception
                                                                        // throws
                                                                        // here
                    writer = new PrintWriter(new OutputStreamWriter(output,
                            "UTF-8"), true); // true = autoFlush, important!
                    String strJson = jsonObject.toString();
                    output.write(strJson.getBytes("UTF-8"));
                    output.flush();
                    System.out.println(htt.getResponseCode());
                    // Read resposne
                    baos = new ByteArrayOutputStream();
                    DataInputStream dis = new DataInputStream(
                            connection.getInputStream());
                    byte[] buffer = new byte[packetSize];// In bytes
                    int realyReaded;
                    double contentSize = connection.getContentLength();
                    double readed = 0L;
                    while ((realyReaded = dis.read(buffer)) > -1) {
                        baos.write(buffer, 0, realyReaded);
                        readed += realyReaded;
                        sendDownloadingMessage(responder, (double) contentSize,
                                readed);
                    }
                    sendCompleteMessage(responder, new InternetResponse(baos,
                            responseCode, url));
                } catch (Exception e) {
                    sendErrorMessage(responseCode, responder, e, url);

                } finally {
                    if (writer != null) {
                        writer.close();
                    }
                }

            }
        }).start();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android / PHP:如何将POST数据从Android发布/获取到PHP - Android/PHP: how to POST/GET JSON data from Android to php 如何从PHP的Android应用程序的post方法解码json数据? - How to decode json data from post method for android app in php? PHP - 如何使用get或post方法抓取外部URL并从中解析json数据? - PHP - how to crawl external url using get or post method and parse json data from it? 使用 Volley 库从 Android 在 PHP 服务器中接收 Json 数据 POST 方法 - Receive Json data POST method in PHP server from Android using Volley Library 在Android中使用JSON从PHP获取数据 - Get Data from PHP using JSON in Android 我如何使用php中的post方法从json数组获取响应 - how i can get response from json array using post method in php 如何在JSON对象中使用POST方法在Laravel中获取数据? - How to get data in Laravel using POST method in JSON Object? 如何使用POST方法从android接收json对象 - how to receive json object from android using POST method 使用get或post方法将json从andriod发送到php并在php中提取json的值 - sending json from andriod to php using get or post method and exatract the values of json in php 如何使用PHP POST方法从Android应用正确将gps数据上传到XAMPP MYSQL? - How to properly upload gps data from android app to XAMPP MYSQL using PHP POST Method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM