2012-10-07 108 views
2

我正在將一些不同的數據收集到我的android程序中具有不同數據類型的三個不同數據中。將數據從Android發佈到php

現在我需要將這些數據發佈到服務器,我應該能夠解析這些數據並將它們存儲在本地數據庫中。我用我的服務器端腳本的PHP。

可以有人給我一個例子如何使用httppost做到這一點?

回答

2

在Android方面你不應該做network operations in the main UI Thread

安卓陣營:

public class SendPOSTRequest extends AsyncTask<List<BasicNameValuePair>, Void, String> 
{ 
    private DefaultHttpClient _httpClient; 
    private String _url = ""; 

    public SendPOSTRequest(String url){ 
     _url = url; 
     _httpClient = new DefaultHttpClient(); 
    } 

    @Override 
    protected String doInBackground(List<BasicNameValuePair>... postParameters) { 
     String responseString = ""; 

     try 
     { 
      HttpPost postRequest = new HttpPost(_url); 
      postRequest.setEntity(new UrlEncodedFormEntity(postParameters[0])); 

      HttpResponse response = _httpClient.execute(postRequest); 
      StatusLine statusLine = response.getStatusLine(); 

      // check if post was successfull 
      if (statusLine.getStatusCode() == HttpStatus.SC_OK) { 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 

       HttpEntity entity = response.getEntity(); 
       entity.writeTo(out); 
       out.close(); 
       responseString = out.toString(); 

       if (entity != null) { 
        entity.consumeContent(); 
       } 
      } 
     } 
     catch(Exception ex) 
     { 
      ex.getMessage(); 
     } 

     return responseString; 
    } 
} 

在你的活動,你可以使用 「SendPostRequest」 一流這樣的: SendPOSTRequest webPOSTRequest =新SendPOSTRequest(yourWebURLWithYourPHPFunction); List postParams = new ArrayList(); postParams.add(new BasicNameValuePair(「Name」,「viperbone」)); String result = webGetRequestUsersEntries.execute(postParams).get();

在服務器端,我使用了帶有PDO(PHP數據對象)的php腳本,因爲it helpts to protect from sql injection

Serverside集團PHP腳本:

try 
{ 
    $DBH = new PDO("mysql:host=yourWebURL;dbname=yourDBName", username, password); 

    # substr(str,pos,len) - Make sure POST-Data aren't too long (255 chars max) because my database-field is 255 chars 
    $NameClear = substr($_POST['Name'], 0, 255); 

    # named placeholders 
    $STH = $DBH->prepare("INSERT INTO `yourTableName` (Name) VALUES (:name)"); 
    $STH->bindParam(':name', $NameClear); 

    # setting the fetch mode 
    $STH->setFetchMode(PDO::FETCH_ASSOC); 
    $STH->execute(); 

    # I return 1 for a successful insertion 
    echo "1"; 

    $DBH = null; 
} 
catch(PDOException $e) { 
} 

我希望它可以幫助...