Android - 使用RESTful api将数据写入数据库

时间:2013-04-13 18:41:31

标签: android json rest http-post restful-architecture

我是初学Android程序员,我正在开发一个从本机设备电话簿中读取联系人并将其写入数据库()的程序。

我可以通过手机阅读和阅读联系人,但我仍然坚持“将联系人写入数据库”。 这是我必须遵循的准则:

write function: 
write: 
[{'activity':'writeData', 
  'firstname':'Janis', 
  'lastname':'Berzins', 
  'telnr': '12312312'}]

request should be sent as: [{'activity':'readData'}]

example for read: [{"firstname":"Vards","lastname":"Uzvards","telnr":"12345678"},{"firstname":"Viesturs","lastname":"Lapsa","telnr":"11223344"}]

我研究了无数教程,文档等等四天,这是我认为应该用于发送到数据库部分的工作:

public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
{
    HttpParams httpParams = new BasicHttpParams();
    HttpClient httpclient = new DefaultHttpClient(httpParams);
    HttpPost request = new HttpPost(url);
    StringEntity s = new StringEntity(c.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    return httpclient.execute(request);
}

为了创建一个简单的测试Json,我使用了这个类:

    public class RestPost extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... params) {
        JSONObject json = new JSONObject();

        try
        {
            json.put("activity", "writeData");
            json.put("firstname", "Janis");
            json.put("lastname", "Berzins");
            json.put("telnr", "123123123");

            RestMethods.doPost(Main.server, json);
        }

        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Error: ", e.toString());
        }
        catch (ClientProtocolException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Error: ", e.toString());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Error: ", e.toString());
        }
        Log.i("DONE ", " I GUES");
        return null;
    }
}

但是在我的Android应用程序执行此功能后 - 数据库()中没有任何变化。

那么,拜托,任何人都可以帮我弄清楚,我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:0)

你需要一个json数组(参见规范中json周围的“[”和“]”字符。

    JSONArray jsonArray = new JSONArray();
    // your code to create the JSONObject
    // ...
    jsonArray.put(json);

    // use this within your RestMethods call
    RestMethods.doPost(Main.server, jsonArray);

你可能可以同时向服务器发送多个对象 - 即使“规范”没有提到它,使用数组也是一种暗示。

答案 1 :(得分:0)

好的,我让它发送到数据库! :) 现在我正在使用Get方法..这就是我得到的 - 现在似乎没有工作,可能是因为数据库中的数据是作为JSONArray发送的?

public static JSONObject doGet(String url)
{
    JSONObject json = null;

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url); 

    httpget.addHeader("accept", "application/json");
    HttpResponse response;

    try {
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();    

        if (entity != null) 
        {
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            json=new JSONObject(result);     
            instream.close();
        }   
    } 

    catch (ClientProtocolException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    } 

    catch (JSONException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    }        

    return json;
}

public static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try 
    {
        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    } 
    finally 
    {
        try 
        {
            is.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    return sb.toString();
}