在我正在创建的Android应用中,我正在尝试以字符串的形式将用户名发送到我的PHP Web服务器。我的代码编译没有错误,我知道我传递给函数的变量不是null(对变量进行烘烤,值是我想要的)。但是,当我尝试使用POST请求获取字符串时,我想要的字符串为null。我该如何检索字符串?
另一方面,我是Android的新手,我不确定天气是不是我应该把它放在一个扩展AsyncTask的类中。我必须在另一个用于从Web服务器检索数据的函数中执行此操作。这是我的代码:
public void sendInfo(String url, String user, String pass){
// Create a new HttpClient and Post Header
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try{
// Add the data
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("username", user));
pairs.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(pairs));
// Execute HTTP Post request
HttpResponse response = client.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
我用来检索帖子的PHP代码:
// ...... Code to connect to database works fine
$new_username = $_POST['username'];
if(is_null($new_username)){
echo 'string is null';
}
echo $new_username;
当我查看网页时,我只看到文字&#34;字符串为空&#34;
答案 0 :(得分:0)
根据HttpClient - Post Method文档,您可能应该使用类似
的内容PostMethod post = new PostMethod(url);
NameValuePair[] data = {
new NameValuePair("username", user),
new NameValuePair("password", password)
};
post.setRequestBody(data);
HttpClient client = new DefaultHttpClient();
client.execute(post);
InputStream in = post.getResponseBodyAsStream();
// handle response...
答案 1 :(得分:0)
我创建了一个AsyncTask的子类来运行函数