发布一个JSON数组在web服务的Andr​​oid数组、JSON、web、oid

2023-09-06 06:32:37 作者:{κυ先笙¥

我有一些问题,什么应该是一个相当简单的任务。我只需要一个JSON数组与单个JSON对象中它被张贴到我的web服务。整个URL请求需要像这样的格式:

I am having some problems with what should be a rather simple task. I simply need a JSON array with a single JSON object within it to be posted to my webservice. The entire URL request needs to be formatted like this:

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

我不能为我的生活弄清楚如何把'location_data使用HttpPost位。这里是一个code片段展示我使用的HTTP连接方法:

I cannot for the life of me figure out how to append the 'location_data' bit using HttpPost. Here is a code snippet to demonstrate the HTTP connection method I am using:

    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();

我没有任何语法错误,我的code为访问服务器很好,只是没有确切的格式服务器的需求。如何格式化我的请求任何帮助,看起来像我需要怎么这将是极大的AP preciated!

I don't have any syntax errors, and my code is accessing the server fine, just not in the exact format the server needs. Any help on how to format my request to look like how I need it would be greatly appreciated!

推荐答案

一后追加键/值数据的URL?就是让不自检。

Appending key/value data to URLs after a '?' is GET not POST.

这是如何发布的Java数据:

This is how to POST data in Java:

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();
}