我在我的android程序中收集了一些不同数据到不同数据类型的三个不同变量。
现在我需要将这些数据发布到服务器中,我应该能够解析这些数据并将它们存储在我的本地数据库中。我正在使用php进行服务器端脚本编写。
有人可以举例说明如何使用httppost进行此操作吗?
答案 0 :(得分:2)
在Android方面,您不应该network operations in the main UI Thread。
Android Side:
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 = new SendPOSTRequest(yourWebURLWithYourPHPFunction); list postParams = new ArrayList(); postParams.add(new BasicNameValuePair(“Name”,“viperbone”)); String result = webGetRequestUsersEntries.execute(postParams).get();
在服务器端,我使用php-script和PDO(PHP数据对象),因为it helpts to protect from sql injection。
Serverside PHP-Script:
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) {
}
我希望它有所帮助...
答案 1 :(得分:2)
向服务器发送请求并获取响应json是实现的最佳方式。
以下是向服务器发送httppost json请求并处理json响应的好例子。
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php