我正在尝试使用JSON将数据库记录从android发送到服务器。 android代码工作正常(没有显示错误)。但是服务器页面中没有显示任何值。下面是android和php代码。
package com.example.income;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.util.*;;
public class Background extends IntentService
{
List<HashMap<String, String>> contacts = new ArrayList<HashMap<String, String>>();
HashMap<String, String> contact = new HashMap<String, String>();
public Background()
{
super("This is the simple background class");
}
@Override
protected void onHandleIntent(Intent intent)
{
Log.v("message","This is simple background service");
Db db =new Db(Background.this,"simple",null,3);
Cursor c= db.getData();
if(c.moveToFirst())
{
do
{
String num,dater;
num = c.getString(c.getColumnIndex("phone_number"));
dater =c.getString(c.getColumnIndex("date"));
contact.put("contact", num);
contact.put("date", dater);
contacts.add(contact);
}
while (c.moveToNext());
try {
sendData();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendData() throws ClientProtocolException, IOException, JSONException
{
Log.v("Let's C","Will it go here?");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.56.1/android.php");
JSONArray array= new JSONArray(contacts);
StringEntity se = new StringEntity(array.toString());
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
HttpResponse response= httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
if(entity!=null)
{
Log.i("response",EntityUtils.toString(entity));
}
}
}
Pho代码
$json = $_POST['HTTP_JSON'];
$data = json_decode($json,true);
print_r($data);
答案 0 :(得分:0)
我建议您不要使用HttpClient,而是使用google自己的排球库,并在其getParams()覆盖方法中返回您的hashmap列表。这样做非常容易。此外,您可以在其setHeader方法中设置标头。