将json对象添加到Java HttpGet请求到C#WebApi

时间:2015-03-14 15:42:04

标签: java c# android json asp.net-web-api

我正在尝试将json对象从java客户端发送到C#WebApi,但输入参数为null。 java代码:

    ObjectMapper mapper = new ObjectMapper();
    Gson gson = new Gson();  
    String json = gson.toJson(per);
    HttpClient httpclient = new DefaultHttpClient();
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("person", json.toString()));
    HttpGet httpPost = new HttpGet("http://naviserver.azurewebsites.net/api/Person/Get?" + URLEncodedUtils.format(qparams, "UTF-8"));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader(
                "Authorization",
                "Bearer TokenRemovedBecauseUseless");


        org.apache.http.HttpResponse httpResponse = httpclient.execute(httpPost);

WebApi方法:

    public List<String> Get([FromUri]Person person)
    {}

有人可以告诉我如何发送json对象吗?

1 个答案:

答案 0 :(得分:2)

问题是WebApi不期望JSON格式的person对象。通过将FromUri与复杂对象一起使用,期望url具有Person中每个字段的查询参数。

关于它是如何工作的,有一个很好的例子here

基本上,您希望查询参数如下所示:

http://naviserver.azurewebsites.net/api/Person/Get?name=dave&age=30

和Java:

qparams.add(new BasicNameValuePair("name", person.getName()));
qparams.add(new BasicNameValuePair("age", String.valueOf(person.getAge())));

如果您想以JSON格式发送此人,更好的方法是使用HTTP POST并在正文中设置JSON。然后在WebApi中,您的方法将如下所示:

public HttpResponseMessage Post([FromBody] Person person)

然后,您还必须更改Java客户端以发送POST请求。

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://naviserver.azurewebsites.net/api/Person");
Person person = new Person("dave", 30);
Gson gson = new Gson();  
String json = gson.toJson(person);
StringEntity body = new StringEntity(json);
httpPost.setEntity(body);
HttpResponse response = httpClient.execute(httpPost);