POST数据到Web服务(PHP,Mysql)时,Android HTTPURLConnection,AsyncTask,doInBackground,HashMap参数不起作用

时间:2019-01-31 08:44:55

标签: android-studio httpurlconnection

我正在尝试通过android Studio中的php将一些数据发送到我的mysql数据库。它无法正常工作,无法找出问题出在哪里。

这是我的MAinActivity.java

package com.shabashams.customerdata;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;


import java.util.HashMap;



public class MainActivity extends AppCompatActivity {

EditText etName,etFathersName,etMothersName,etCustomersAddress,etCustomersOccupation,etPreferredBranch,etTypeOfAccount,etNid,etMobileNo,etEmail;     私有字符串customerName =“”,fathersName =“”,mothersName =“”,customerOccupation =“”,customersAddress =“”,preferredBranch =“”,typeofAccount =“”,customersNID =“”,mobileNo =“”,eMail =“ “;

    Button btnSendRequest;



    private JSONObject json;
    private int success = 0;
    private HTTPURLConnection service;

    private String path = "http://172.20.10.4/~shams/testrmandroid/receive.php";


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

        etName = findViewById(R.id.etName);
        etFathersName = findViewById(R.id.etFathersName);
        etMothersName = findViewById(R.id.etMothersName);
        etCustomersAddress = findViewById(R.id.etCustomersAddress);
        etCustomersOccupation = findViewById(R.id.etCustomersOccupation);
        etPreferredBranch = findViewById(R.id.etPreferredBranch);
        etTypeOfAccount = findViewById(R.id.etTypeOfAccount);
        etNid = findViewById(R.id.etNid);
        etMobileNo = findViewById(R.id.etMobileNo);
        etEmail = findViewById(R.id.etEmail);


        btnSendRequest = findViewById(R.id.btnSendRequest);



        service=new HTTPURLConnection();

        btnSendRequest.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {



                customerName = etName.getText().toString().trim();
                fathersName = etFathersName.getText().toString().trim();
                mothersName = etMothersName.getText().toString().trim();
                customersAddress = etCustomersAddress.getText().toString().trim();
                customerOccupation = etCustomersOccupation.getText().toString().trim();
                preferredBranch = etPreferredBranch.getText().toString().trim();
                typeofAccount = etTypeOfAccount.getText().toString().trim();
                customersNID = etNid.getText().toString().trim();
                mobileNo = etMobileNo.getText().toString().trim();
                eMail = etEmail.getText().toString().trim();

                new PostDataTOServer().execute();
            }

        });
    }


    private class PostDataTOServer extends AsyncTask<Void, Void, Void> {

        String response = "";

        //HashMap<String, String> params;

        protected void onPreExecute(){}

        @Override
        protected Void doInBackground(Void... voids) {

            HashMap<String, String> params = new HashMap<>();
            params.put("customerName", customerName);
            params.put("fathersName", fathersName);
            params.put("mothersName", mothersName);
            params.put("customerOccupation", customerOccupation);
            params.put("customersAddress", customersAddress);
            params.put("customersNID", customersNID);
            params.put("typeofAccount", typeofAccount);
            params.put("mobileNo", mobileNo);
            params.put("eMail", eMail);
            params.put("preferredBranch", preferredBranch);

            response = service.ServerData(path, params);
            try {

                json = new JSONObject(response);

                System.out.println("success=" + json.get("success"));
                success = json.getInt("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (success == 1) {
                Toast.makeText(getApplicationContext(), "Customer Added Successfully.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Could not add customer.", Toast.LENGTH_LONG).show();
            }
        }

    }

}

here is my HTTPURLConnection.java

package com.shabashams.customerdata;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;


public class HTTPURLConnection {
    String response="";
    URL url;

    public String ServerData(String path,HashMap<String, String> params) {
        try {
            url = new URL(path);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            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(params));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                //Log.d("Output",br.toString());
                while ((line = br.readLine()) != null) {
                    response += line;
                    Log.d("output lines", line);
                }
            } else {
                response = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

这是我的php代码

<?php
include('connection.php');


$customerName=$_POST['customerName'];
$fathersName=$_POST['fathersName'];
$mothersName=$_POST['mothersName'];
$customerOccupation=$_POST['customerOccupation'];
$customersAddress=$_POST['customersAddress'];
$customersNID=$_POST['customersNID'];
$typeofAccount=$_POST['typeofAccount'];
$mobileNo=$_POST['mobileNo'];
$eMail=$_POST['eMail'];
$preferredBranch=$_POST['preferredBranch'];


$success=0;

$query = "INSERT INTO  customer (customerName, fathersName, mothersName, customerOccupation, customersAddress, customersNID, typeofAccount, mobileNo, eMail, preferredBranch) 
VALUES ('$customerName','$fathersName','$mothersName','$customerOccupation','$customersAddress','$customersNID','$typeofAccount','$mobileNo','$eMail','$preferredBranch')";


//$result = mysqli_query($mysqli,$query);

if(mysqli_query($connection,$query))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
?>

0 个答案:

没有答案