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

我正在尝试测试我的 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",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>

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

解决方法

你正在加倍你的协议:

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,这显然是错误的.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...