麻烦从Android发送JSON到ASP.NET Web API

时间:2013-12-28 06:36:56

标签: android json asp.net-web-api

我正在尝试将一些JSON数据发送到这样的asp.net web api控制器(来自here):

  JSONObject Parent = new JSONObject();

        Parent.put("enterpriseId", "55e8a2a3-466d-46dc-95ce-bc5f2d3e7828");
        List<Integer> lst = new ArrayList<Integer>();
        lst.add(1);
        lst.add(2);
        lst.add(3);
        lst.add(4);
        lst.add(5);
        Parent.put("itemids", lst);

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(Financial.AccountReviewUrl+"/testtesttest");

        StringEntity se;
        se = new StringEntity(Parent.toString());
        //Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json; charset=utf-8");
        httpPostRequest.setHeader("AuthenticationToken", Financial.UserEncrypt); 

        Log.d("json is", Parent.toString());
        Log.d("use encryp is", Financial.UserEncrypt);


        return httpclient.execute(httpPostRequest);

我的网络API操作:

        [HttpPost]
        public Object TestTestTest(Guid enterpriseId, List<int> itemIds)
        {
            var count = 0;
            if (itemIds != null)
                count = itemIds.Count;

            return enterpriseId.ToString() + ":" + count.ToString();

        }

我一直收到404错误。我知道之前曾多次询问过,但推荐的答案似乎都不适合我。有什么想法吗?

我看到thisthis并且......回答但是对我不起作用

1 个答案:

答案 0 :(得分:2)

您的API需要表单帖子而不是JSON对象。对于POST JSON对象,您将执行以下操作

// Code snippet for posting JSONObject
HttpPost httpPost = new HttpPost(serviceUrl);
MultipartEntity multipartEntity = new MultipartEntity();    
multipartEntity.addPart("data", new StringBody(jsonObject.toString()));
httpPost.setEntity(multipartEntity);
try {
    HttpResponse response = httpClient.execute(httpPost);
} catch (Exception ex) {
    // Log the error
}

由于您的代码需要URL编码表单数据,因此您将按如下方式执行此操作

// Code snippet for posting form data
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serviceUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (int i = 0; i < params.length; i++) {
    nameValuePairs.add(new BasicNameValuePair(params[i], values[i]));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs);
httpPost.setEntity(formEntity);
try {
    HttpResponse response = httpClient.execute(httpPost);
} catch (Exception ex) {
    // Log the error
}

在第二个代码段中,您将构建两个NameValuePair个对象,一个用于enterpriseId,另一个用于itemids

PS:这些是代码段,您必须根据使用情况对其进行修改。

希望这有帮助。