使用REST API - 发送帖子,接收JSON

时间:2015-02-19 15:23:05

标签: android json rest

我试图在Android中使用REST API,但响应返回nil ...而在Web客户端和iOS Client中,它返回的JSON字典

我的代码:

  final Handler h = new Handler();
    final Runnable r1 = new Runnable() {

        @Override
        public void run() {
            System.out.println("onClick!!!");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://applocalize.com.br/rest/rest.php");
            post.setHeader("content-type", "application/text; charset=UTF-8");
            post.setHeader("Accept", "application/json");
            //Construimos el objeto cliente en formato JSON
            JSONObject dato = new JSONObject();

            try {
                dato.put("pg","categorias");
                dato.put("serv", "buscar");
                dato.put("dt_atualizacao", "0`");

                StringEntity entity = new StringEntity(dato.toString());
                post.setEntity(entity);
                HttpResponse resp = httpClient.execute(post);
                String respStr = EntityUtils.toString(resp.getEntity());
                if (resp.getStatusLine().getStatusCode() == 200)
                {
                    System.out.println(respStr);
                    JSONArray temp1 = new JSONArray(respStr);
                }
                System.out.println("OKAY!");
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    h.postDelayed(r1, 5000);

1 个答案:

答案 0 :(得分:1)

您的后端似乎在您的帖子请求中期待ValuePairs,但您正在发送正文中的原始jsonobject。试试这个:

 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 nameValuePairs.add(new BasicNameValuePair("pg","categorias"));
 nameValuePairs.add(new BasicNameValuePair("serv","buscar"));
 nameValuePairs.add(new BasicNameValuePair("dt_atualizacao","0"));
 try{
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }catch (UnsupportedEncodingException e){

        }