我有一个非常简单的代码无效。我只是想从Android应用程序发送一个字符串到PHP服务器。没有什么花哨。我寻找类似的问题,但我没有想出任何东西。 我没有得到问题,logcat没有给出任何错误,一切似乎工作正常,但当我运行我的PHP脚本并发送字符串时,它不会发生任何事情。
这是我应用的代码
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("your_string", yourString));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(""); //my correct script adress
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Context context = getApplicationContext();
CharSequence text = "Succesfully uploaded!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是php服务器
<?php
if (isset($_POST['your_string']) && $_POST['your_string'] != '') {
$your_string = $_POST['your_string'];
echo 'received the string: ' . $your_string;
} else {
echo 'empty';
}
?>
答案 0 :(得分:1)
你是否正在运行你的Android代码异步?考虑使用Async Task。
还要确保添加内容类型标题:
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
您还可以检查服务器响应并进行记录,以便了解问题所在,如下所示:
Log.d("Res",EntityUtils.toString(httpResponse.getEntity()));
祝你好运;)