2017-10-08 162 views
-1

我目前正在開發一個項目,我必須將數據添加到mysql數據庫。我使用Microsoft Azure作爲我的主機,一切工作正常。我得到的唯一問題是,當我嘗試使用「發佈」Web請求添加數據時,我沒有收到任何錯誤,但沒有添加任何內容。使用web請求將數據添加到mysql數據庫Android

這是我在Android Studio代碼,再沒有任何錯誤:

package com.example.antoinedepommereau.livre; 



public class Login extends AppCompatActivity { 

public static Dialog mydiag; 
public static Button SignUpButton; 
public static EditText firstnameTxt; 
public static EditText lastnameTxt; 
public static EditText emailsignupTxt; 
public static EditText passwordsignupTxt; 
public static EditText confirmpasswordTxt; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.content_login); 

    Button LoginButton = (Button) findViewById(R.id.btn_login); 

    final TextView SignUpText = (TextView) findViewById((R.id.link_signup)); 
    final EditText emailTxt = (EditText)findViewById(R.id.input_email); 
    final EditText passwordTxt = (EditText)findViewById(R.id.input_password); 


    SignUpText.setOnClickListener(new View.OnClickListener(){ 
     public void onClick(View v){ 
      showDialog(); 
     } 
    }); 

    LoginButton.setOnClickListener(new View.OnClickListener(){ 
     public void onClick(View v){ 
      if("".equals(emailTxt.getText().toString())){ 
       emailTxt.setError("Email adress is required!"); 
       return;    } 

      if("".equals(passwordTxt.getText().toString())){ 
       passwordTxt.setError("Password is required!"); 
       return; 
      } 

      /* Intent startActivitylivre = new Intent(Login.this, livremain.class); 
      startActivity(startActivitylivre);*/ 
     } 
    }); 

} 

private void showDialog() 
{ 
    final Dialog mydiag = new Dialog(this); 

    //set the title 
    mydiag.setTitle("Sign Up"); 

    //inflate the layout 
    mydiag.setContentView(R.layout.fragment_sign_up); 

    mydiag.show(); 

    SignUpButton = (Button) mydiag.findViewById(R.id.btn_signup); 
    firstnameTxt = (EditText)mydiag.findViewById(R.id.login_firstname); 
    lastnameTxt = (EditText)mydiag.findViewById(R.id.login_lastname); 
    emailsignupTxt = (EditText)mydiag.findViewById(R.id.login_email); 
    passwordsignupTxt = (EditText)mydiag.findViewById(R.id.login_password); 
    confirmpasswordTxt = (EditText)mydiag.findViewById(R.id.login_passwordconfirm); 

    SignUpButton.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      if ("".equals(firstnameTxt.getText().toString())) { 
       firstnameTxt.setError("Your first name is required!"); 
       return; 
      } 

      if ("".equals(lastnameTxt.getText().toString())) { 
       lastnameTxt.setError("Your last name is required!"); 
       return; 
      } 

      if ("".equals(emailsignupTxt.getText().toString())) { 
       emailsignupTxt.setError("You must enter a valid email adress!"); 
       return; 
      } 

      /* if(passwordsignupTxt.getText().toString() != confirmpasswordTxt.getText().toString()){ 
       confirmpasswordTxt.setError("Passwords are not matching"); 
       return; 
      }*/ 
      try { 
       getText(); 
      } 

      catch (Exception e) { 
       Toast.makeText(getApplicationContext(), "Url expection!", Toast.LENGTH_LONG).show(); 
      } 
     } 
    }); 
} 


public void getText() throws UnsupportedEncodingException{ 

    String name = firstnameTxt.getText().toString(); 
    String email = emailsignupTxt.getText().toString(); 
    String password = confirmpasswordTxt.getText().toString(); 

    String data = URLEncoder.encode("Name", "UTF-8") 
      + "=" + URLEncoder.encode(name, "UTF-8"); 

    data += "&" + URLEncoder.encode("Email", "UTF-8") + "=" 
      + URLEncoder.encode(email, "UTF-8"); 

    data += "&" + URLEncoder.encode("Password", "UTF-8") 
      + "=" + URLEncoder.encode(password, "UTF-8"); 

    String text = ""; 
    BufferedReader reader=null; 

    // Send data 
    try 
    { 

     // Defined URL where to send data 
     URL url = new URL("http://hitachipick.azurewebsites.net/SQLQuery.php"); 

     // Send POST data request 

     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write(data); 
     wr.flush(); 

     // Get the server response 

     reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     // Read Server Response 
     while((line = reader.readLine()) != null) 
     { 
      // Append server response in string 
      sb.append(line + "\n"); 
     } 


     text = sb.toString(); 
    } 
    catch(Exception ex) 
    { 

    } 
    finally 
    { 
     try 
     { 

      reader.close(); 
     } 

     catch(Exception ex) {} 
    } 

    confirmpasswordTxt.setText(text); 
} 

}

然後我的PHP代碼:

<?php 
$servername = "eu-cdbr-azure-north-e.cloudapp.net"; 
$username = "bdbad7b3d3b2da"; 
$password = "39d98912"; 
    try 
{ 
     $conn = new PDO("mysql:host=$servername;dbname=Hitachi",$username, 
     $password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     echo "connected succesfully"; 
} 
catch(PDOException $e) 
{ 
     echo "Connection failed: " . $e->getMessage(); 
} 

if (isset($_POST['Name']) && isset($_POST['Email']) && 
isset($_POST['Password'])){ 
//Insert new contact into database 
$query = $conn->prepare('INSERT INTO contact_info (contact_name, 
contact_email, contact_password) VALUES (:name, :email, :password)'); 
$query->execute([ 
    ':name' => $_POST['Name'], 
    ':email' => $_POST['Email'], 
    ':password' => $_POST['Password'] 
]); 
echo"done"; 
} 
?> 

到數據庫的連接工作正常因爲我得到「連接成功」,但沒有添加到數據庫中。我不知道問題來自哪裏。

希望你能幫助,

感謝您的幫助。

編輯:

現在,我使用拉維的代碼:`字符串urlParameters = 「NAME =」 +名字+ 「&電子郵件= 」+電子郵件+「 &密碼」 +密碼;

 byte[] postData  = urlParameters.getBytes(StandardCharsets.UTF_8); 
     int postDataLength = postData.length; 

     String request  = "http://hitachipick.azurewebsites.net/SQLQuery.php"; 
     URL url   = new URL(request); 
     HttpURLConnection conn= (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setInstanceFollowRedirects(false); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     conn.setRequestProperty("charset", "utf-8"); 
     conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 
     conn.setUseCaches(false); 
     try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { 
      wr.write(postData); 
      Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show(); 
     }` 

但它仍然沒有工作....我添加了一個抓來查看錯誤日誌貓:

android.os.NetworkOnMainThreadException 
                         at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303) 
                         at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86) 
                         at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74) 
                         at java.net.InetAddress.getAllByName(InetAddress.java:752) 
                         at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29) 
                         at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:209) 
                         at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:163) 
                         at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:105) 
                         at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:489) 
                         at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465) 
                         at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371) 
                         at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:503) 
                         at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130) 
                         at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:261) 
                         at com.example.antoinedepommereau.livre.Login.getText(Login.java:173) 
                         at com.example.antoinedepommereau.livre.Login$3.onClick(Login.java:134) 
                         at android.view.View.performClick(View.java:6261) 
                         at android.widget.TextView.performClick(TextView.java:11185) 
                         at android.view.View$PerformClick.run(View.java:23752) 
                         at android.os.Handler.handleCallback(Handler.java:751) 
                         at android.os.Handler.dispatchMessage(Handler.java:95) 
                         at android.os.Looper.loop(Looper.java:154) 
                         at android.app.ActivityThread.main(ActivityThread.java:6776) 
                         at java.lang.reflect.Method.invoke(Native Method) 
                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 

我很堅持,, pleasse hellpp ...

+0

你去上班'done'? – Ravi

+0

否....它不執行查詢.... –

+0

這意味着您需要調試您是否在'POST'中獲得價值 – Ravi

回答

0

如果var_dump($POST)打印null,這意味着,當您的請求正在構建時您有問題。

另外,我注意到,你沒有在你的代碼中指定請求類型。所以,可能只是指定

conn.setRequestMethod("POST"); 

如果仍然不起作用,那麼請使用下面的代碼,這對我有用。

// specify parameter and their value 
String urlParameters = "param1=a&param2=b&param3=c"; 

byte[] postData  = urlParameters.getBytes(StandardCharsets.UTF_8); 
int postDataLength = postData.length; 

String request  = "http://hitachipick.azurewebsites.net/SQLQuery.php"; 
URL url   = new URL(request); 
HttpURLConnection conn= (HttpURLConnection) url.openConnection();   
conn.setDoOutput(true); 
conn.setInstanceFollowRedirects(false); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("charset", "utf-8"); 
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 
conn.setUseCaches(false); 
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { 
    wr.write(postData); 
} 
+0

它仍然無法正常工作......我編輯了問題以添加諸如logcats等信息。但是,非常感謝 –

+0

@AntoinedePommereau你在這裏失蹤了'='在這裏簽字'「&Password」+ password;' – Ravi

+0

仍然得到一個android.os.NetworkOnMainThreadException錯誤。我真的不明白錯誤來自哪裏 –

0

設法得到它使用AsinTask類

類sendFeedback擴展的AsyncTask {

@Override 
    protected String doInBackground(String[] params) { 
     // do above Server call here 


     ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
     postParameters.add(new BasicNameValuePair("Name", name)); 
     postParameters.add(new BasicNameValuePair("Email", email)); 
     postParameters.add(new BasicNameValuePair("Password", password)); 

     String responseString = null; 

     try 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://hitachipick.azurewebsites.net/SQLQuery.php"); 

      // no idea what this does :) 
      httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 

      // This is the line that send the request 
      HttpResponse response = httpclient.execute(httppost); 

      HttpEntity entity = response.getEntity(); 

      InputStream is = entity.getContent(); 
     } 
     catch (Exception e) 
     { 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 

     return""; 
    } 

    @Override 
    protected void onPostExecute(String message) { 
     //process message 
    } 


}