gpt4 book ai didi

android - 无法使用本地主机将数据从应用程序传输到mysql

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:29:24 31 4
gpt4 key购买 nike

我正在尝试测试我的 Android 应用程序并将数据添加到本地主机上托管的数据库。我使用 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);
}

}

添加用户.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>

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

最佳答案

你正在加倍你的协议(protocol):

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 - 无法使用本地主机将数据从应用程序传输到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21964401/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com