对于这种交互,我使用以下代码:
public static String httpPost(String address, List<NameValuePair> parameters) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(address);
InputStream inputStream = null;
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
reader = new BufferedReader((new InputStreamReader(inputStream)));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (reader != null)
reader.close();
if (inputStream != null)
inputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
您必须传递这个函数 aString
这是 PHP 脚本的 URL,以及一个NameValuePair
包含要传递给脚本的数据的 s 列表,它会从服务器返回答案。
如果你想用它来登录,你可以使用类似的东西:
public boolean login(String username, String passwd) {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username);
parameters.add(new BasicNameValuePair("password", passwd);
String result = httpPost("http://test.com/login.php", parameters);
return result.equals("ok");
}