我有两个字符串,如何将两个字符串从安卓代码传递给php?我有以下代码来连接我的 php:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.101/webservice/index.php");
HttpResponse response = httpclient.execute(httppost);
例如,您是否尝试过以这种方式使用 GET?
HttpClient httpclient = new DefaultHttpClient();
String string1 = "A";
String string2 = "B";
HttpPost httppost = new HttpPost("http://192.168.1.101/webservice/index.php?string1=" + string1 + "&string2=" + string2);
HttpResponse response = httpclient.execute(httppost);
例如,在 PHP 中:
<?php
$string1 = $_GET["string1"]);
$string2 = $_GET["string2"]);
?>
这样做:
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("StringOne", stringOne));
nameValuePairs.add(new BasicNameValuePair("StringTwo", stringTwo));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
在 PHP 中:
<?php
$stringOne = $_POST["StringOne"];
$stringTwo = $_POST["StringTwo"];
?>
使用此代码片段。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("dataOne", "Hello"));
nameValuePairs.add(new BasicNameValuePair("dataTwo", "Android World"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
首先,您需要实现一个 AsyncTask 来配置此任务。您可以找到有关如何在Android开发人员上实现AsyncTask的更多信息|异步任务。
然后在方法 doInBackground(String...strings)
中:
@Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://example.gr/yourscript.php?id="+id+
"&anotherParam="+param) //send parameteres to php script
.build();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
System.out.println(responseString);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return x;
}
您还应该有一个 php 脚本,您可以在其中获取需要通过 GET 传递的参数。例如 $id = $_GET['id'];