0

我有从 url 解析 json 内容并完成它们的 android 要求,现在我需要将结果作为 json 内容发送回服务器 url。搜索了许多以前的帖子,但大多数都指定了如何下载和解析 json 内容。任何关于如何开始在 json 中将内容发布到 url 的输入/示例都会有很大的帮助!

编辑:下面是我正在尝试的示例代码

try {

        URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

执行此操作时,连接被拒绝,java.net.connect 异常!请帮忙!!

4

1 回答 1

1

您可以使用以下方法发送您的 JSON 请求。

public static HttpResponse sendRequest(String url, String request) throws Exception 
{
    //Create the httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //create an HttpPost request object
    HttpPost httpost = new HttpPost(url);

    //Create the String entity to be passed to the HttpPost request
    StringEntity se = new StringEntity(request));

    //set the created StringEntity
    httpost.setEntity(se);

    //the intended
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    return httpclient.execute(httpost);
}

希望这可以帮助。

于 2013-03-25T17:05:00.967 回答