我是Android编程的新手,但对PHP有很好的了解。
我正在尝试通过邮寄请求将数据发送到我的服务器。我有以下代码:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inps = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inps));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
inps.close();
result=sb.toString();
Log.v("data-received",result);
我在互联网上的许多地方都找到了代码。
在PHP方面,我写这个:
<?php
echo "something".$_REQUEST['year'];
?>
但我只是在我的应用程序结束时输出了“某些东西”(在日志值“数据接收”中)?
我做错了什么?我是否需要设置任何环境变量等?
答案 0 :(得分:0)
$_REQUEST
并非始终受支持,请使用$_GET
或$_POST
,具体取决于参数所在的位置。
答案 1 :(得分:0)
我使用这段代码将日期发送到php文件。这是使用POST。我希望你能用它做点什么......
URL url;
try {
url = new URL("url.nl/phppage.php");
InputStream myInputStream =null;
StringBuilder sb = new StringBuilder();
//adding some data to send along with the request to the server
// Data below:
sb.append("email="+email.getText().toString()+"&name="+name.getText().toString()+"&message="+om.getText().toString());
//url = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn
.getOutputStream());
// this is were we're adding post data to the request
wr.write(sb.toString());
wr.flush();
myInputStream = conn.getInputStream();
wr.close();
Context context = getApplicationContext();
Log.i("TAG", "Message send successful");
CharSequence text = "Message send successful";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
finish();
} catch (Exception e) {
Context context = getApplicationContext();
Log.e("TAG", "Message not sended - SERVER POST ERROR");
CharSequence text = "Message couldn't be send.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
答案 2 :(得分:0)
在代码中已经是一个检查,他在成功时给出了一个Toast消息和一个日志。在php服务器上你可以使用print_r($_POST);
这应该没问题。你现在使用的代码是什么?
答案 3 :(得分:0)
我终于开始工作了。唯一的变化是在第一行:
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePairs>();
而不是
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
有人知道为什么会有效吗?