2016-05-13 85 views
0

我正在嘗試使用php將包括params在內的android與mysql連接起來。Android發送字符串到PHP

我發現了可以工作的php代碼。但我不明白爲什麼不工作android的代碼。我在logcat中沒有收到錯誤。

MainActivity:

... 
boton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       sendMessage("mensaje"); 
      } 
     }); 
    } 


    public void sendMessage(String t){ 

     ServerRequests serverRequests = new ServerRequests(this); 
     serverRequests.fetchUserDataAsyncTask(t);{ 
      Log.d("", "sendMessage: "+t); 
     }; 
    } 
... 

ServerRequest

> public class ServerRequests { 
> 
>  URL url; 
>  HttpURLConnection conn; 
>  ProgressDialog progressDialog; 
>  String mensaje; 
> 
>  public ServerRequests(Context context) { 
>   progressDialog = new ProgressDialog(context); 
>   progressDialog.setCancelable(false); 
>   progressDialog.setTitle("Authenticating..."); 
>   progressDialog.setMessage("Please wait..."); 
>  } 
> 
>  public void fetchUserDataAsyncTask(String mensaje) { 
>   progressDialog.show(); 
>   new fetchUserDataAsyncTask(mensaje,"hola").execute(); 
>  } 
> 
>  public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, String> { 
> 
>   String returnedUser; 
> 
> 
>   public fetchUserDataAsyncTask(String mensaje, String returnedUser) { 
> 
>   } 
> 
>   @Override 
>   protected String doInBackground(Void... params) { 
> 
>    try { 
> 
>     url = new URL("http://gclimb.com/androidphp/index.php"); 
> 
>     conn = (HttpURLConnection) url.openConnection(); 
>     String param = "mensaje="+mensaje; 
>     conn.setRequestMethod("POST"); 
>     conn.setDoInput(true); 
>     conn.setDoOutput(true); 
>     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
>     conn.setRequestProperty("charset", "UTF-8"); 
>     conn.connect(); 
> 
>     OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); 
>     out.write(param); 
> 
>     //No code to receive response yet, want to get the POST working first. 
> 
>    } 
>    catch (MalformedURLException e) { 
>     e.printStackTrace(); 
>    } catch (ProtocolException e) { 
>     e.printStackTrace(); 
>    } catch (IOException e) { 
>     e.printStackTrace(); 
>    } 
>    catch (Exception e) { 
> 
>    } finally { 
>     progressDialog.dismiss(); 
>    } 
> 
>    return returnedUser; 
>   } 
>  } 
> 
> } 

編輯

這是一個簡單的index.php文件。

PHP文件:

<?php 

$mensaje = $_POST['username']; 
$mensaje2 = $_POST['password']; 
$bo = $mensaje; 
$servername = "zzzzzzz"; 
$username = "zzzzzz"; 
$password = "zzzzz"; 
$dbname = "zzzzz"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "INSERT INTO AndroidPhp (mensaje) VALUES ('$bo')"; 
$conn->query($sql); 





$sql2="SELECT mensaje FROM AndroidPhp"; 

$result = $conn->query($sql2); 

if ($result->num_rows > 0) { 
    // output data of each row 
    while($row = $result->fetch_assoc()) { 
     echo $row["mensaje"]; 
    } 
} else { 
    echo "0 results"; 
} 

?> 
+0

你可以嘗試'conn.connect()'後你'write' PARAMS爲'OutputStream' –

回答

0

使用排庫。這很簡單。

樣品:Volley Library

你可以找到my answer了。

+0

嗨@Sathish。我嘗試複製你的答案的代碼,但在我的情況下,對話框說:「JSON錯誤」,「服務器錯誤..!嘗試過一段時間..!」 – Cofeina

+0

根據您的需要善意修改。檢查你的網址是否正常工作 –

+0

是的,網址工作正常。 – Cofeina

0

WsHttpPost.java

public class WSHttpPost extends AsyncTask<String, Void, String> { 
ProgressDialog pDialog; 
Context context; 
HttpURLConnection httpConnection; 
ContentValues values; 
public WSHttpPost(Context context, ContentValues values) { 
    // TODO Auto-generated constructor stub 
    this.context = context; 
    this.values = values; 
} 

@Override 
protected void onPreExecute() { 
    // TODO Auto-generated method stub 
    super.onPreExecute(); 
    pDialog = new ProgressDialog(context); 
    pDialog.setTitle("Connecting..."); 
    pDialog.setMessage("Please Wait..."); 
    pDialog.setCancelable(false); 
    pDialog.show(); 
} 

@Override 
protected String doInBackground(String... params) { 
    // TODO Auto-generated method stub 
    String result = ""; 
    try { 
     URL url = new URL(params[0]); 
     httpConnection = (HttpURLConnection) url.openConnection(); 
     httpConnection.setRequestProperty("Accept", "application/json"); 
     //httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     httpConnection.setReadTimeout(10000); 
     httpConnection.setConnectTimeout(15000); 
     httpConnection.setRequestMethod("POST"); 
     httpConnection.setDoInput(true); 
     httpConnection.setDoOutput(true); 

     OutputStream os = httpConnection.getOutputStream(); 
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
     writer.write(String.valueOf(values)); 
     writer.flush(); 
     writer.close(); 
     os.close(); 

     int responseCode = httpConnection.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      InputStream iStream = httpConnection.getInputStream(); 
      InputStreamReader isReader = new InputStreamReader(iStream); 
      BufferedReader br = new BufferedReader(isReader); 
      String line; 
      while ((line = br.readLine()) != null) { 
       result += line; 
      } 
     } 
    } catch (java.net.SocketTimeoutException e) { 
     Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show(); 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
     Log.e("Error : ", e.toString()); 
    } 
    return result; 
} 

@Override 
protected void onPostExecute(String result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
    pDialog.dismiss(); 
    try { 
     Toast.makeText(context, result, Toast.LENGTH_SHORT).show(); 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
     Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

調用

boton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      ContentValues cv = new ContentValues(); 
      cv.put("mensaje",mensaje); 
      WsHttpPost httpPost = new WsHttpPost(MainActivity.this,cv); 
      httpPost.execute("http://gclimb.com/androidphp/index.php"); 
      } 
     }); 
    } 

不要忘記在的Manifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 
+0

我試着用你的代碼。當點擊按鈕只在logcat中有這條消息時:sendUserActionEvent()mView == null,並在屏幕上顯示一個空的麪包。 – Cofeina

+0

你在休息控制中檢查你的回答嗎? – Rushvi

+0

我檢查那裏,我得到錯誤的HTML代碼響應 – Rushvi

0

我能看到的是你的問題添加權限沒有持有責任e從服務器返回。您正在返回returnedUser,但您是否檢查了此變量包含的內容?

你可以看到下面的方法,或者你可以使用任何磁帶庫通信服務器。

您可以爲此用戶RetroFit或Volley。

參見這些例子:

http://www.truiton.com/2015/04/android-retrofit-tutorial/

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

public String executePost(String targetURL, String urlParameters) { 
    URL url; 
    HttpURLConnection connection = null; 
    StringBuffer response = new StringBuffer(); 
    try { 
     // Create connection 

     url = new URL(targetURL); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded"); 

     connection.setRequestProperty("Content-Length", 
       "" + Integer.toString(urlParameters.getBytes().length)); 

     connection.setUseCaches(false); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setConnectTimeout(timeout); 
     connection.setReadTimeout(timeout); 


     // Send request 
     DataOutputStream wr = new DataOutputStream(
       connection.getOutputStream()); 
     wr.writeBytes(urlParameters); 

     wr.flush(); 
     wr.close(); 

     // Get Response 
     InputStream is = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 

     while ((line = rd.readLine()) != null) { 
      response.append(line); 
      response.append('\r'); 
     } 
     rd.close(); 
     //Log.v("JSON ", " " + response.toString()); 
     return response.toString(); 

    } catch (SocketTimeoutException ex) { 
     ex.printStackTrace(); 

    } catch (MalformedURLException ex) { 
     Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
     // Log.v("JSON ", " " + response.toString()); 
    } catch (UnknownHostException e) { 
     e.printStackTrace(); 
     // Log.v("JSON ", " " + response.toString()); 
    } catch (IOException ex) { 

     Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     // Log.v("JSON ", " " + response.toString()); 
    } finally { 

     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
    return null; 
}