无法使用localhost将数据从app传输到mysql

时间:2014-02-23 05:00:07

标签: android android-asynctask android-async-http

我正在尝试测试我的Android应用程序并将数据添加到localhost上托管的数据库中。我使用ngrok打开了一个隧道来访问存储在我本地计算机上的数据库。这是我的代码:

public class MainActivity extends FragmentActivity{
        private DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;

        private static String email;
        // nav drawer title
        private CharSequence mDrawerTitle;

        // used to store app title
        private CharSequence mTitle;

        // slide menu items
        private String[] navMenuTitles;
        private TypedArray navMenuIcons;

        private ArrayList<NavDrawerItem> navDrawerItems;
        private NavDrawerListAdapter adapter;

        private static final int RESULT_SETTINGS = 1;
        private static String IP_ADDRESS="http://682dc364.ngrok.com/";

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

            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

            Account[] accounts = AccountManager.get(getBaseContext()).getAccounts();

            if(accounts.length > 0)
                 email = accounts[0].name;
            Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
            mTitle = mDrawerTitle = getTitle();

            addUser();

              }
        private static void addUser()
        {
            HashMap<String, String> nameValuePairs = new HashMap<String, String>();

            nameValuePairs.put("email",email);
            String id="addUser";
            AsyncHttpPost asyncHttpPost = new AsyncHttpPost(nameValuePairs);
            asyncHttpPost.execute(id,"http://"+IP_ADDRESS+"/MakeMyDay/add_user.php");
        }

AsyncHttpPost

public class AsyncHttpPost extends AsyncTask<String, String, String> 
{
    private HashMap<String,String> mData=null;


    public AsyncHttpPost(HashMap<String,String> data)
    {
        mData=data;
    }

    @Override
    protected String doInBackground(String... params)
    {
        //JSONObject obj=getLocationInfo(mData.get("address"));
        //getLatLong(obj);
        //String lat=Double.toString(latitude);
        //String lon=Double.toString(longitude);
        //mData.put("Latitude", lat);
        //mData.put("Longitude", lon);


        HttpURLConnection connection;
        OutputStreamWriter request = null;

        ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        Iterator<String> it = mData.keySet().iterator();

        String parameters="";

        while (it.hasNext()) {
            String key = it.next();
            String value=mData.get(key);
            parameters=parameters+key+"="+value+"&";
            Log.d("key",key);
            Log.d("value",mData.get(key));
            Log.d("string value",value);
            nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
        }

        parameters=parameters.substring(0, parameters.length()-1);
        Log.d("parameters",parameters);

        URL url = null;   
        String response = null;
        String id="";
        try
        {
            id=params[0];
            url = new URL(params[1]);               
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST"); 
            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();


            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n"); 
            }

            // Response from server after login process will be stored in response variable.

            response = sb.toString();   

            String s=regExExtractor(response);


            // You can perform UI operations here
            Log.d("server message","Message from Server: \n"+ response);
            Log.d("progress","here3");
            isr.close();
            reader.close();
        }        

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

    public String regExExtractor(String response)
    {
        String jsonResponse="";

        Pattern p=Pattern.compile("(\\Q[\\E.*?\\Q]\\E)");
        Matcher m=p.matcher(response);
        while(m.find())
        {
            jsonResponse=m.group(1);
        }

        return jsonResponse;
    }


    /*@Override
    protected String doInBackground(String... params)
    {

        ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        Iterator<String> it = mData.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next();
            String value=mData.get(key);
            Log.d("key",key);
            Log.d("value",mData.get(key));
            Log.d("string value",value);
            nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
        }

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");

        try {
            // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
            //This is typically useful while sending an HTTP POST request. 
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePair);

            // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
            post.setEntity(urlEncodedFormEntity);

            try {
                // HttpResponse is an interface just like HttpPost.
                //Therefore we can't initialize them
                HttpResponse httpResponse = client.execute(post);

                // According to the JAVA API, InputStream constructor do nothing. 
                //So we can't initialize InputStream although it is not an interface
                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);
                }
                Log.d("server response",stringBuilder.toString());
                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;
    }*/

    @Override
    protected void onPostExecute(String result) {
        // something...
        //textView.setText(result);
    }

}

add_user.php

<?php 

$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser   = 'xxxx';
$DBPass   = 'xxxx';
$DBName   = 'xxxx';

$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}

$sql="SELECT email FROM user WHERE email='$email'";

$rs=$conn->query($sql);

if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
  $rows_returned = $rs->num_rows;
  if($rows_returned==0)
  {
    $sql="INSERT INTO user (email) VALUES ($email)";
    if($conn->query($sql) === false) {
      trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
    } else {
      $last_inserted_id = $conn->insert_id;
      $affected_rows = $conn->affected_rows;
    }
  }
}
$conn->close();
?>

服务器消息如下:

Message from Server: 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="refresh" content="0;url=http://search.maxonline.com.sg/main?InterceptSource=0&ClientLocation=sg&ParticipantID=zflj3p94j2yfy45e433eet7iejjmxgif&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fhttp%2F%2F682dc364.ngrok.com%2F%2FMakeMyDay%2Fadd_user.php&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0"/><script type="text/javascript">url="http://search.maxonline.com.sg/main?InterceptSource=0&ClientLocation=sg&ParticipantID=zflj3p94j2yfy45e433eet7iejjmxgif&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fhttp%2F%2F682dc364.ngrok.com%2F%2FMakeMyDay%2Fadd_user.php&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0";if(top.location!=location){var w=window,d=document,e=d.documentElement,b=d.body,x=w.innerWidth||e.clientWidth||b.clientWidth,y=w.innerHeight||e.clientHeight||b.clientHeight;url+="&w="+x+"&h="+y;}window.location.replace(url);</script></head><body></body></html>

有谁知道为什么这不起作用

2 个答案:

答案 0 :(得分:6)

你的协议加倍:

asyncHttpPost.execute(id,"http://"+IP_ADDRESS+"/MakeMyDay/add_user.php");

private static String IP_ADDRESS="http://682dc364.ngrok.com/";

给出http://http://682dc364.ngrok.com//MakeMyDay/add_user.php,这显然是错误的。

答案 1 :(得分:1)

你可以尝试使用Ion发送http请求,更少的代码和更简单的https://github.com/koush/ion