将数据从android发送到ScriptePHP和Response

时间:2012-02-20 16:15:45

标签: java php android http-post

让我解释一下这个场景:

我想通过使用我的一个原生Android应用程序将一些机密数据发送到其他服务器。在服务器端,有一个PHP页面监听我传递的参数并获取相关数据。

这是我的Java代码:

package com.http7;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Http7Activity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    private EditText usernameEditText;
    private Button send;
    private String givenUsername;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        usernameEditText = (EditText) findViewById(R.id.go);
        send = (Button) findViewById(R.id.b1);
        send.setOnClickListener(this);
    }
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        givenUsername = usernameEditText.getEditableText().toString();
        //System.out.println("Given username :" + givenUsername );
        sendPostRequest(givenUsername);
    }
     private void sendPostRequest(String givenUsername){
         /*-----------------------------------------------------------------1-----------------------------------*/

         class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
             /*----------------------------------------------------2-----------------------------------*/
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                 /*---------------------------------------3-----------------------------------*/
                String paramUsername = params[0];
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://localhost/test/test.php");
                BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("p", paramUsername);
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(1);
                nameValuePairList.add(usernameBasicNameValuePair);
                try {  
                    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
                    httpPost.setEntity(urlEncodedFormEntity);
                    try {
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        InputStream inputStream = httpResponse.getEntity().getContent();
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        StringBuilder stringBuilder = new StringBuilder();
                        String bufferedStrChunk = null;
                        while((bufferedStrChunk = bufferedReader.readLine()) != null){
                            stringBuilder.append(bufferedStrChunk);
                        }
                        return stringBuilder.toString();
                        }catch (ClientProtocolException cpe) {
                        //System.out.println("First Exception caz of HttpResponese :" + cpe);
                        cpe.printStackTrace();
                        }catch (IOException ioe) {
                               //System.out.println("Second Exception caz of HttpResponse :" + ioe);
                               ioe.printStackTrace();
                        }
                    }catch (UnsupportedEncodingException uee) {
                        //System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                        uee.printStackTrace();
                    }
                return null;
                 /*---------------------------------------3-----------------------------------*/
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                if(result.equals("working")){
                    Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
                }
            }



             /*---------------------------------------------------2------------------------------------*/
         }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(givenUsername);



         /*-------------------------------------------------------------------1----------------------------------*/
     }
}

这是PHP代码:

<?php
$varUsername = $_POST['p'];
if($varUsername == "bilhip"){
    echo 'working';
}else{
    echo 'invalid';
}
?>

1 个答案:

答案 0 :(得分:0)

我不知道问题是什么,但localhost指向模拟器(或Android手机),而不是本地机器,可能是您的PHP / Apache服务器。

如果您使用的是模拟器let's have a look at the particular IPs (section "Emulator networking")