简体   繁体   English

如何从Android发送字符串到PHP

[英]how to send string from Android to php

i was trying to create an online apps. 我试图创建一个在线应用程序。 I would like to send a string from my apps to my PHP script, but it ended up with the php doesn't receive any string from my apps, which means the PhP will echo back NULL. 我想从我的应用程序发送一个字符串到我的PHP脚本,但它结果是php没有从我的应用程序接收任何字符串,这意味着PhP将回显NULL。 I have been doing research online and searching for solution, but none of them worked. 我一直在网上进行研究并寻找解决方案,但都没有奏效。

Below is my MainActivity.java code: 下面是我的MainActivity.java代码:

package my.com.tutionathome.calvinlau.testserver;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button b;
    EditText et;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;

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

        b = (Button)findViewById(R.id.Button01);
        et= (EditText)findViewById(R.id.EditText01);
        tv= (TextView)findViewById(R.id.tv);

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
                Thread thread = new Thread()
                {
                    @Override
                    public void run() {
                        try{

                            httpclient=new DefaultHttpClient();
                            httppost= new            HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
                            //add your data
                            nameValuePairs = new ArrayList<NameValuePair>(1);
                            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
                            nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $"username" = $_POST['username'];
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            //Execute HTTP Post Request
                            response=httpclient.execute(httppost);

                            ResponseHandler<String> responseHandler = new BasicResponseHandler();
                            final String response = httpclient.execute(httppost, responseHandler);
                            System.out.println("Response : " + response);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    p.dismiss();
                                    tv.setText("Response from PHP : " + response);
                                }
                            });

                        }catch(Exception e){

                            runOnUiThread(new Runnable() {
                                public void run() {
                                    p.dismiss();
                                }
                            });
                            System.out.println("Exception : " + e.getMessage());
                        }
                    }
                };

                thread.start();


            }
        });
    }
}

And my php code: 我的PHP代码:

<?php
        // put your code here
        $hostname_localhost ="localhost";
    $database_localhost ="android";
    $username_localhost ="root";
    $password_localhost ="";
    $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
    or
    trigger_error(mysql_error(),E_USER_ERROR);

    mysql_select_db($database_localhost, $localhost);

    $username = $_POST['username'];
    $password = $_POST['password'];
    $query_search = "select Email, Username from tblmember where Username = '".$username."' AND Email = '".$password. "'";
    $query_exec = mysql_query($query_search) or die(mysql_error());
    $rows = mysql_num_rows($query_exec);

    if($username == NULL){
        echo "NULL";
    }else{
        echo $username; 
    }
        ?>

This is my Android Manifest : 这是我的Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="my.com.tutionathome.calvinlau.testserver">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

有很多库来促进这一点,节省了许多代码行,我特别建议改造

Try this Code. 试试这个代码。

AysncyTask AysncyTask

private class AysncyTask extends AsyncTask<Void,Void,Void>
    {
        private ProgressDialog regDialog=null;
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            regDialog=new ProgressDialog(this);
            regDialog.setTitle(getResources().getString(R.string.app_name));
            regDialog.setMessage(getResources().getString(R.string.app_pleasewait));
            regDialog.setIndeterminate(true);
            regDialog.setCancelable(true);
            regDialog.show();
        }       
        @Override
        protected Void doInBackground(Void... params) {
            try 
            {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();



                        postParameters.add(new BasicNameValuePair("username",
                                et.getText().toString().trim()));

  postParameters.add(new BasicNameValuePair("password",
                                etpass.getText().toString().trim()));





                        String response = null;
                        try {
                            response = SimpleHttpClient
                                    .executeHttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php",
                                            postParameters);
                             res = response.toString();

                             return res;

                        } catch (Exception e) {
                            e.printStackTrace();
                            errorMsg = e.getMessage();
                        }
                    }
                }).start();
                try {
                    Thread.sleep(3000);


                //  error.setText(resp);
                    if (null != errorMsg && !errorMsg.isEmpty()) {

                    }
                } catch (Exception e) {
                }

            } 
            catch (Exception e) 
            {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            if(regDialog!=null)
            {

                regDialog.dismiss();

            //do you code here you want

                }

  // do what u do
    }

SimpleHttpClient.java SimpleHttpClient.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class SimpleHttpClient {
 /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
    }

    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
        sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    }
    finally {
        if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }
    }


    public static String executeHttpatch(String url, ArrayList<NameValuePair> postParameters) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
        sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    }
    finally {
        if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
        sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    }
    finally {
        if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM