Java XML Data Type Converter sendJson(URL url, String method, String data, String user, String password)

Here you can find the source of sendJson(URL url, String method, String data, String user, String password)

Description

send Json

License

Apache License

Declaration

public static String sendJson(URL url, String method, String data, String user, String password)
            throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String sendJson(URL url, String method, String data, String user, String password)
            throws IOException {
        final StringBuffer buffer = new StringBuffer();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        //authentication
        String userpass = user + ":" + password;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        connection.setRequestProperty("Authorization", basicAuth);

        //send json data
        connection.setRequestMethod(method);

        if (data != null) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(data);/*from w w w.  jav  a2  s.  com*/
            writer.flush();
            writer.close();
        }

        //read response
        final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line = reader.readLine();
        while (line != null) {
            buffer.append(line);
            line = reader.readLine();
        }

        reader.close();

        return buffer.toString();
    }
}

Related

  1. printPriceType(Long value)
  2. printZahl20(BigInteger value)
  3. printZahl31(BigDecimal value)
  4. printZimmeranzahl(BigDecimal value)
  5. readKey(Reader reader, String algorithm)
  6. serializeLogic(Serializable logic)
  7. serializeToString(Object object)
  8. serializeURLSafe(String string)
  9. stringToCalendar(String value)