[英]sending the data in Json android Namevaluepair to the php server
我想发送在列表中存储有姓名和电话号码的联系方式,为此,我正在将该列表转换为NameValuePairs。 现在,我想将其发送到PHP服务器,并将这些详细信息保存在数据库中。 仅出于测试目的,我目前正在将此文件写入文件,还返回到android检查数据。 下面是我的代码:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
HttpPost post = new HttpPost("xyz.com");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (ContactRetreive cr : al)
{
nameValuePairs.add(new BasicNameValuePair("name", cr.name));
nameValuePairs.add(new BasicNameValuePair("phone",cr.phone));
}
Log.i("NameValuePair", nameValuePairs.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
Log.i("Read from Server", a);
}
} catch (Exception e) {
e.printStackTrace();
}
public String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
Log.i("ConvertoStream", "Starting");
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Stream Exception",
Toast.LENGTH_SHORT).show();
}
Log.i("ConvertoStream", "Result:" + total.toString());
return total.toString();
}
下面是我的PHP代码块
$json = file_get_contents('php://input');
$obj = json_decode($json);
$file = fopen("fileOutput1.txt","w");
echo fwrite($file,$obj);
foreach ($obj as $item)
{
echo $item['name'];
}
The issue is
1. It is not writing anything on file that means the data I am passing from the android is not reading in the php.
2. It is returning the error in the android : Invalid argument supplied to ForEach loop.
请帮助我,我无法找出问题所在。 如果您需要任何东西,请告诉我。
要在php中获取name
和phone
,请使用$_REQUEST
或array_values($_POST)
作为:
$arr_obj = array_values($_POST);
现在使用arr_obj
数组获取从android应用程序发布的所有值。
使用$_REQUEST
:
$name=$_REQUEST['name'];
$phone=$_REQUEST['phone'];
编辑:使用BasicNameValuePair
将数组传递给php:
for (ContactRetreive cr : al)
{
nameValuePairs.add(new BasicNameValuePair("name[]", cr.name));
nameValuePairs.add(new BasicNameValuePair("phone[]",cr.phone));
}
在PHP中使用$_POST
获得数组:
$arr_name = array($_POST[name]);
$arr_phone = array($_POST[phone]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.