集册 Java实例教程 将JSON发布到URL

将JSON发布到URL

欢马劈雪     最近更新时间:2020-01-02 10:19:05

569
将JSON发布到URL


//package com.nowjava;/**来自 N o w  J a v a  . c o m**/


import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;


import java.io.Reader;

import java.io.Writer;

import java.net.HttpURLConnection;

import java.net.ProtocolException;

import java.net.URL;


public class Main {

    public static void postJSON(String json, URL endpoint, Writer output)

            throws Exception {

        HttpURLConnection urlc = null;

        try {
        /**
         * 时代Java公众号 提 供 
        **/

            urlc = (HttpURLConnection) endpoint.openConnection();


            try {

                urlc.setRequestMethod("POST");

            } catch (ProtocolException e) {

                throw new Exception(

                        "Shouldn't happen: HttpURLConnection doesn't support POST??",

                        e);

            }


            urlc.setDoOutput(true);

            urlc.setDoInput(true);

            urlc.setUseCaches(false);

            urlc.setAllowUserInteraction(false);

            urlc.setRequestProperty("Content-type", "application/xml;"); //"text/xml; charset=" + "UTF-8");

            OutputStream out = urlc.getOutputStream();


            try {

                Writer writer = new OutputStreamWriter(out, "UTF-8");

                writer.write(json);

                writer.flush();

                writer.close();

            } catch (IOException e) {

                throw new Exception("IOException while posting data", e);

            } finally {

                if (out != null)

                    out.close();

            }


            InputStream in = urlc.getInputStream();

            try {

                Reader reader = new InputStreamReader(in);

                pipe(reader, output);

                reader.close();

            } catch (IOException e) {

                throw new Exception("IOException while reading response", e);

            } finally {

                if (in != null)

                    in.close();

            }

        } catch (IOException e) {

            throw new Exception("Connection error (is server running at "

                    + endpoint + " ?): " + e);

        } finally {

            if (urlc != null)

                urlc.dis
展开阅读全文