如何使用Body Content调用API

时间:2013-08-15 09:31:17

标签: android api

我试图像

那样得到帖子回复
StringEntity  entity;
private static final int TIMEOUT_MILLISEC = 20000;
private static final String serverurl = "http://appcodetechnology.net/meravenue/api/";

在函数m下面调用

  post("master_details.php");

//

public String post(String request)
    {
        String result = null;
        try
        {   
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
            HttpClient client = new DefaultHttpClient(params);
            System.out.println("Getting url: "+request);
            HttpPost post = new HttpPost(serverurl+request);

             String body  = "{\"action\":\"get_all_cities\"}";

                try {
                    //entity = new StringEntity("action=" + java.net.URLEncoder.encode(body, "utf-8"));                     
                    //entity = new StringEntity("data=" + java.net.URLEncoder.encode(body, "utf-8"));                       
                     entity = new StringEntity(java.net.URLEncoder.encode(body, "utf-8"));                          
                     entity.setContentType("application/x-www-form-urlencoded");

                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
               // entity.setContentType("application/x-www-form-urlencoded");
                post.setEntity(entity);


            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if(entity != null)
            {
                result = EntityUtils.toString(entity);
            }
            else
            {
                Log.d("Response Failed","Response from server is failed");
            }

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
    }

和回应

{"result":false,"message":"Invalid method name.","error_code":"406"}

我没有任何错误。

以下API工作

URL : http://appcodetechnology.net/meravenue/api/master_details.php
Method : POST
Request Body : {"action":"get_all_cities"}

但没有得到回复

1 个答案:

答案 0 :(得分:1)

使用此命令发布json对象:

                JSONObject json = new JSONObject();
                json.put("YOUR_KEY", YOUR_VALUE);
                post.setEntity(new ByteArrayEntity(json .toString().getBytes("UTF8")));

或者只是参考此页面来了解如何发布json:

How to send a JSON object over Request with Android?