簡體   English   中英

帶有PHP服務器響應的HttpClient JSONData POST請求

[英]HttpClient JSONData POST Request with Response for PHP Server

我正在嘗試使用hyperlink將數據發送到PHP Server,並希望將發送的數據顯示到同一hyperlink

在運行應用程序並單擊按鈕后,我得到了一個帶有響應Toastreceived: received: Array

我的MainActivity.Java

package com.vtgames.intuitionsoftwares.jsonwebservice;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;

import javax.net.ssl.HttpsURLConnection;


public class MainActivity extends Activity {

    Button bt;
    TextView txt;




    // Response
    String responseServer;

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

        txt = (TextView) findViewById(R.id.raw);
        bt = (Button) findViewById(R.id.sendData);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            new SendPostRequest().execute();
            }
        });
    }


    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {

            try {

                URL url = new URL("https://******.com/name2.php"); // here is your URL path

                JSONObject postDataParams = new JSONObject();
                postDataParams.put("name", "MyName");
                postDataParams.put("email", "myname@gmail.com");
                Log.e("params",postDataParams.toString());

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(new
                            InputStreamReader(
                            conn.getInputStream()));

                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            }
            catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();
        }
    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }

}

和我的Server PHP Code **name2.php**

<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
$Data_array_received = array();
$Data_array_received = $_POST;
$Data_received_from_array= $Data_array_received["params"];
echo "received:  ".$Data_received_from_array;
echo "received:  ".$Data_array_received;
print_r($_POST);

?>

LogCat:

01-19 15:12:29.070 24381-24381/vn.vtgames.jsonwebservice I/View: Touch down dispatch to android.widget.Button{42033b78 VFED..C. ........ 16,37-752,85 #7f020002 app:id/sendData}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=449.29562, y[0]=27.144348, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=1090691373, downTime=1090691373, deviceId=2, source=0x1002 }
01-19 15:12:29.087 24381-24381/vn.vtgames.jsonwebservice D/OpenGLRenderer: prepareDirty (0.00, 0.00, 768.00, 976.00) opaque 1 <0x6b2ea490>
01-19 15:12:29.089 24381-24381/vn.vtgames.jsonwebservice D/OpenGLRenderer: finish <0x6b2ea490>
01-19 15:12:29.191 24381-24381/vn.vtgames.jsonwebservice I/View: Touch up dispatch to android.widget.Button{42033b78 VFED..C. ...P.... 16,37-752,85 #7f020002 app:id/sendData}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=449.29562, y[0]=27.144348, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=1090691495, downTime=1090691373, deviceId=2, source=0x1002 }
01-19 15:12:29.196 24381-24402/vn.vtgames.jsonwebservice E/params: {"email":"abc@gmail.com","name":"abc"}
01-19 15:12:29.197 24381-24402/vn.vtgames.jsonwebservice D/dalvikvm: create interp thread : stack size=128KB
01-19 15:12:29.197 24381-24402/vn.vtgames.jsonwebservice D/dalvikvm: create new thread
01-19 15:12:29.198 24381-24402/vn.vtgames.jsonwebservice D/dalvikvm: new thread created
01-19 15:12:29.198 24381-24402/vn.vtgames.jsonwebservice D/dalvikvm: update thread list
01-19 15:12:29.198 24381-25355/vn.vtgames.jsonwebservice D/dalvikvm: threadid=13: interp stack at 0x6c13b000
01-19 15:12:29.198 24381-25355/vn.vtgames.jsonwebservice D/dalvikvm: threadid=13: created from interp
01-19 15:12:29.198 24381-24402/vn.vtgames.jsonwebservice D/dalvikvm: start new thread
01-19 15:12:29.198 24381-25355/vn.vtgames.jsonwebservice D/dalvikvm: threadid=13: notify debugger
01-19 15:12:29.198 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:1
01-19 15:12:29.198 24381-25355/vn.vtgames.jsonwebservice D/dalvikvm: threadid=13 (OkHttp ConnectionPool): calling run()
01-19 15:12:29.198 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:1
01-19 15:12:29.198 24381-24402/vn.vtgames.jsonwebservice D/NativeCrypto: ssl=0x6c12dc18 sslRead buf=0x421149d0 len=1500,timeo=10
01-19 15:12:29.208 24381-24381/vn.vtgames.jsonwebservice D/OpenGLRenderer: prepareDirty (0.00, 0.00, 768.00, 976.00) opaque 1 <0x6b2ea490>
01-19 15:12:29.209 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:15000
01-19 15:12:29.209 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:15000
01-19 15:12:29.209 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:15000
01-19 15:12:29.209 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:15000
01-19 15:12:29.209 24381-24381/vn.vtgames.jsonwebservice D/OpenGLRenderer: finish <0x6b2ea490>
01-19 15:12:29.212 24381-24402/vn.vtgames.jsonwebservice D/NativeCrypto: ssl=0x6c12dc18 sslWrite buf=0x42114fc0 len=286 write_timeout_millis=0
01-19 15:12:29.214 24381-24402/vn.vtgames.jsonwebservice D/NativeCrypto: ssl=0x6c12dc18 sslRead buf=0x421149d0 len=1500,timeo=15000
01-19 15:12:29.445 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:100
01-19 15:12:29.445 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:100
01-19 15:12:29.445 24381-24402/vn.vtgames.jsonwebservice D/NativeCrypto: ssl=0x6c12dc18 sslRead buf=0x421149d0 len=1500,timeo=100
01-19 15:12:29.446 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:100
01-19 15:12:29.446 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:100
01-19 15:12:29.446 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:100
01-19 15:12:29.446 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:100
01-19 15:12:29.446 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:15000
01-19 15:12:29.447 24381-24402/vn.vtgames.jsonwebservice I/System.out: [CDS]rx timeout:15000
01-19 15:12:29.507 24381-24381/vn.vtgames.jsonwebservice D/GraphicBuffer: create handle(0x6c12c1f8) (w:224, h:47, f:1)
01-19 15:12:32.956 24381-24381/vn.vtgames.jsonwebservice D/GraphicBuffer: close handle(0x6c12c1f8) (w:224 h:47 f:1)

現在,一旦我打開鏈接,我將看到:“ received:received:Array”在Toast我在顯示Response的地方再次看到:“ received:received:Array”

但是我想在鏈接以及響應中顯示{"email":"abc@gmail.com","name":"abc"}

因此,請在我做錯地方幫助我。

您應該使用類似翻新的庫: http : //square.github.io/retrofit/或Fast-Android-Networking: https : //github.com/amitshekhariitbhu/Fast-Android-Networking或android-async-http: http: //loopj.com/android-async-http/

要發布,將數據獲取到服務器並進行調試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM