私はいくつかの異なるデータを私のAndroidプログラムの異なるデータ型の3つの異なる変数に収集しています。
次に、このデータをサーバーに投稿する必要があります。サーバーでこのデータを解析して、ローカルデータベースに保存できるはずです。サーバーサイドスクリプトにphpを使用しています。
httppostを使用してこれを行う方法の例を教えてもらえますか?
私はいくつかの異なるデータを私のAndroidプログラムの異なるデータ型の3つの異なる変数に収集しています。
次に、このデータをサーバーに投稿する必要があります。サーバーでこのデータを解析して、ローカルデータベースに保存できるはずです。サーバーサイドスクリプトにphpを使用しています。
httppostを使用してこれを行う方法の例を教えてもらえますか?
Android側では、メインUIスレッドでネットワーク操作を実行しないでください。
Android側:
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」-次のようなクラスを使用できます。SendPOSTRequestwebPOSTRequest = new SendPOSTRequest(yourWebURLWithYourPHPFunction); リストpostParams=new ArrayList(); postParams.add(new BasicNameValuePair( "Name"、 "viperbone")); 文字列の結果=webGetRequestUsersEntries.execute(postParams).get();
サーバーサイドでは、SQLインジェクションから保護するのに役立つため、PDO(PHPデータオブジェクト)でphp-scriptを使用しました。
サーバーサイド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) {
}
お役に立てば幸いです...
サーバーにリクエストを送信してレスポンスを取得するには、jsonが実装するのに最適な方法です。
これは、httppost jsonリクエストをサーバーに送信し、jsonレスポンスを処理するための良い例です。
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php