将JSON数组发布到Android中的webservice

时间:2010-04-08 06:06:24

标签: java android eclipse json

我在应该做一个相当简单的任务时遇到一些问题。我只需要一个JSON数组,其中包含一个JSON对象即可发布到我的webservice。整个URL请求需要格式化如下:

http://www.myserver.com/myservice.php?location_data=[{"key1":"val1","key2":"val2"....}]

我不能为我的生活弄清楚如何使用HttpPost追加'location_data'位。 这是一个代码片段,用于演示我正在使用的HTTP连接方法:

    HttpClient hClient = new DefaultHttpClient();
    HttpPost hPost = new HttpPost(url);

    try {
        hPost.setEntity(new StringEntity(string));
        hPost.setHeader("Accept", "application/json");
        hPost.setHeader("Content-type", "application/json");

        //execute request
        HttpResponse response = (HttpResponse) hClient.execute(hPost);
        HttpEntity entity = response.getEntity();

HttpClient hClient = new DefaultHttpClient(); HttpPost hPost = new HttpPost(url); try { hPost.setEntity(new StringEntity(string)); hPost.setHeader("Accept", "application/json"); hPost.setHeader("Content-type", "application/json"); //execute request HttpResponse response = (HttpResponse) hClient.execute(hPost); HttpEntity entity = response.getEntity();

我没有任何语法错误,我的代码正在访问服务器,只是没有服务器所需的格式。任何有关如何格式化我的请求看起来像我需要它的帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

在'?'之后将键/值数据附加到网址是没有POST。

这是在Java中POST数据的方法:

String urlText = "http://www.myserver.com/myservice.php";
String postContent = "location_data=[{\"key1\":\"val1\",\"key2\":\"val2\"}]";
try {
  HttpURLConnection c = (HttpURLConnection) new URL(urlText).openConnection();
  c.setDoOutput(true);
  OutputStreamWriter writer = new OutputStreamWriter(c.getOutputStream(), "UTF-8");
  writer.write(postContent);
  writer.close();
} catch (IOException e) {
  e.printStackTrace();
}