Android 无法使用localhost将数据从应用程序传输到mysql
我正在尝试测试我的android应用程序,并将数据添加到本地主机上托管的数据库中。我用ngrok打开了一个隧道,以访问存储在本地计算机上的数据库。这是我的密码:Android 无法使用localhost将数据从应用程序传输到mysql,android,android-asynctask,android-async-http,Android,Android Asynctask,Android Async Http,我正在尝试测试我的android应用程序,并将数据添加到本地主机上托管的数据库中。我用ngrok打开了一个隧道,以访问存储在本地计算机上的数据库。这是我的密码: public class MainActivity extends FragmentActivity{ private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerTogg
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");
}
public类MainActivity扩展了FragmentActivity{
私人抽屉布局mDrawerLayout;
私有列表视图mDrawerList;
私有操作bardrawertoggle mDrawerToggle;
私有静态字符串电子邮件;
//导航抽屉标题
私有字符序列mDrawerTitle;
//用于存储应用程序标题
私有字符序列mTitle;
//幻灯片菜单项
私有字符串[]navMenuTitles;
专用型雷达导航仪;
私人ArrayList NavWrites;
专用导航适配器;
私有静态最终整数结果_设置=1;
专用静态字符串IP_地址=”http://682dc364.ngrok.com/";
@SuppressLint(“新API”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences SharedPrefers=PreferenceManager.getDefaultSharedPreferences(此);
Account[]accounts=AccountManager.get(getBaseContext()).getAccounts();
如果(accounts.length>0)
电子邮件=帐户[0]。名称;
Toast.makeText(此,电子邮件,Toast.LENGTH_SHORT).show();
mTitle=mDrawerTitle=getTitle();
addUser();
}
私有静态void addUser()
{
HashMap nameValuePairs=新HashMap();
nameValuePairs.put(“电子邮件”,email);
String id=“addUser”;
AsyncHttpPost AsyncHttpPost=新的AsyncHttpPost(nameValuePairs);
asyncHttpPost.execute(id,“http://“+IP_ADDRESS+”/MakeMyDay/add_user.php”);
}
异步HttpPost
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);
}
}
公共类AsyncHttpPost扩展了AsyncTask
{
私有HashMap mData=null;
公共异步HttpPost(哈希映射数据)
{
mData=数据;
}
@凌驾
受保护的字符串doInBackground(字符串…参数)
{
//JSONObject obj=getLocationInfo(mData.get(“地址”);
//getLatLong(obj);
//字符串纬度=双精度。toString(纬度);
//字符串lon=Double.toString(经度);
//mData.put(“纬度”,纬度);
//mData.put(“经度”,lon);
httpurl连接;
OutputStreamWriter请求=null;
ArrayList nameValuePair=新的ArrayList();
迭代器it=mData.keySet().Iterator();
字符串参数=”;
while(it.hasNext()){
String key=it.next();
字符串值=mData.get(键);
参数=参数+键+“=”+值+“&”;
Log.d(“键”,键);
Log.d(“value”,mData.get(key));
Log.d(“字符串值”,值);
添加(新的BasicNameValuePair(key,mData.get(key));
}
parameters=parameters.substring(0,parameters.length()-1);
Log.d(“参数”,参数);
URL=null;
字符串响应=null;
字符串id=“”;
尝试
{
id=params[0];
url=新url(参数[1]);
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(真);
connection.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
connection.setRequestMethod(“POST”);
请求=新的OutputStreamWriter(connection.getOutputStream());
请求。写入(参数);
request.flush();
request.close();
字符串行=”;
InputStreamReader isr=新的InputStreamReader(connection.getInputStream());
BufferedReader读取器=新的BufferedReader(isr);
StringBuilder sb=新的StringBuilder();
而((line=reader.readLine())!=null)
{
sb.追加(第+行“\n”);
}
//登录过程后来自服务器的响应将存储在响应变量中。
response=sb.toString();
字符串s=regExExtractor(响应);
//您可以在此处执行UI操作
Log.d(“服务器消息”,“来自服务器的消息:\n”+响应);
日志d(“进度”,“此处3”);
isr.close();
reader.close();
}
捕获(客户端协议异常cpe){
System.out.println(“HTTPResponse的第一个例外caz:+cpe”);
printStackTrace();
}捕获(ioe异常ioe){
System.out.println(“HttpResponse的第二个异常caz:+ioe”);
ioe.printStackTrace();
}
返回响应;
}
公共字符串regExExtractor(字符串响应)
{
字符串jsonResponse=“”;
模式p=Pattern.compile(\\Q[\\E.\\Q]\\E);
匹配器m=p.Matcher(响应);
while(m.find())
{
jsonResponse=m组(1);
}
返回jsonResponse;
}
/*@凌驾
受保护的字符串doInBackground(字符串…参数)
{
ArrayList nameValuePair=新的ArrayList();
迭代器it=mData.keySet().Iterator();
while(it.hasNext()){
String key=it.next();
字符串值=mData.get(键);
Log.d(“键”,键);
Log.d(“value”,mData.get(key));
Log.d(“字符串值”,值);
添加(新的BasicNameValuePair(key,mData.get(key));
}
HttpClient=new DefaultHttpClient();
HttpPost=newhttppost(参数[0]);//在本例中,参数[0]是URL
post.addHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
试一试{
//UrlEncodedFormEntity是由url编码对列表组成的实体。
//这通常很有用
<?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/";