duanbeng6709 2018-01-19 09:43
浏览 132

具有响应PHP服务器的HttpClient JSONData POST请求

I'm Trying to send data to PHP Server with a hyperlink and want to display the sent data to the same hyperlink.

After I run the application and onClicking the Button I get a Toast with Response: received: received: Array

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

}

And My 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)

Now once I open the link I see: "received: received: Array" In Toast I'm Displaying Response where again I see: "received: received: Array"

But I want to display {"email":"abc@gmail.com","name":"abc"} in Link as well as in Response.

So, Please help me where I'm doing mistake.

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计