2013-04-27 77 views
1

我希望我的應用程序通過查詢字符串發送兩個字符串到一個php文件,它將把它們作爲POST變量處理。通過Android的HttpRequest發送簡單POST

到目前爲止,我有這樣的代碼

public void postData() {  
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31"); 

    try { 

    HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

我認爲這是一個難以解決的問題,但它是我的第一個Android應用程序,我會很感激所有幫助。

回答

2

使用nameValuePairs在POST請求中傳遞數據。

試試這樣說:

public void postData() { 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php"); 

    try { 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "123")); 
     nameValuePairs.add(new BasicNameValuePair("string", "Hey")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // Catch Protocol Exception 
    } catch (IOException e) { 
     // Catch IOException 
    } 
}