2013-04-26 61 views
1

我想從我的android代碼發送一些數據到php文件。從android發送數據到php,可能是數據沒有達到php結束

,並試圖從PHP回來取,並在模擬器 我的Java代碼

`

 try{ 

     URL url = null; 
     String s="http://10.0.2.2/welcome.php"; 
    url = new URL(s); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("GET"); 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(s);  
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
                          HttpResponse response = httpclient.execute(httppost); 

     Log.i("postData", response.getStatusLine().toString()); 
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
       stringBuilder = new StringBuilder(); 

       String line = null; 
       while ((line = reader.readLine()) != null) 
       { 
       stringBuilder.append(line + "\n"); 
       } 
     } 

     catch(Exception e) 
     { 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 


     finally 
     { 
      tx.setText(stringBuilder.toString()); 
      // close the reader; this can throw an exception too, so 
      // wrap it in another try/catch block. 
      if (reader != null) 
      { 
      try 
      { 
       reader.close(); 
      } 
      catch (IOException ioe) 
      { tx.setText((CharSequence) ioe); 
       ioe.printStackTrace(); 
      } 
      } 
     }`` 

我被打開兩個不同的連接一個職位,另一個用於獲取做了愚蠢顯示它,但問題不在於此。它與我的http-post.execute方法。

我的PHP代碼 <?php $pLat = $_POST['pLat']; $pLng = $_POST['pLng']; print_r("$_POST['pLat']"); print_r("$_POST['pLng']"); ?>

我想我已經在我的發送數據,怎麼有問題,如果我贊同在我的PHP sumthing它顯示在我的模擬器。

請幫忙

回答

1

我真的建議您使用庫來執行HTTP請求。事情變得更容易。以Android Asynchronous Http Client爲例。一個POST數據和處理響應的例子:

AsyncHttpClient client = new AsyncHttpClient(); 
RequestParams rp = new RequestParams(); 
rp.put("pLat", "some value"); 
rp.put("pLong", "some other value"); 
client.post("http://10.0.2.2/welcome.php", rp, new AsyncHttpResponseHandler() { 
    @Override 
    public final void onSuccess(String response) { 
     // handle your response here 
    } 

    @Override 
    public void onFailure(Throwable e, String response) { 
     // something went wrong 
    }    
}); 
+0

謝謝britzl,你的ans真的幫了我.. n amy代碼現在運行良好。 – yug 2013-04-26 09:09:18

+0

,我還添加了aysnc http客戶端jar文件。非常感謝。再次:) – yug 2013-04-26 09:10:00

+0

太棒了。我很樂意提供幫助。您可能想要upvote並接受答案。 – britzl 2013-04-26 10:43:33