Java Resource File put(String resource, Map headers, String data)

Here you can find the source of put(String resource, Map headers, String data)

Description

put

License

LGPL

Declaration

public static byte[] put(String resource, Map<String, String> headers, String data) throws IOException 

Method Source Code

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

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Map;
import java.util.Map.Entry;

public class Main {
    private static final int HTTP_CONNECT_TIMEOUT = 15000;
    private static final int HTTP_READ_TIMEOUT = 20000;
    private static final int BUF_SIZE = 65536;

    public static byte[] put(String resource, Map<String, String> headers, String data) throws IOException {
        URL url;/*from w w  w. j a  v a 2 s .co  m*/
        ByteArrayOutputStream baos = null;
        OutputStreamWriter wr = null;
        try {
            url = new URL(resource);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
            urlConnection.setReadTimeout(HTTP_READ_TIMEOUT);

            fillHeaders(urlConnection, headers);
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(data);
            wr.flush();

            baos = new ByteArrayOutputStream();
            InputStream inputStream = urlConnection.getInputStream();

            byte[] buffer = new byte[BUF_SIZE];
            int bufferLength = 0;

            while ((bufferLength = inputStream.read(buffer)) > 0) {
                baos.write(buffer, 0, bufferLength);
            }
            return baos.toByteArray();
        } finally {
            if (baos != null)
                baos.close();
            if (wr != null)
                wr.close();
        }
    }

    public static void fillHeaders(HttpURLConnection urlConnection, Map<String, String> headers) {
        if (headers == null)
            return;

        for (Entry<String, String> entry : headers.entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
}

Related

  1. loadConfigFile(String resource, Class clazz)
  2. loadUTF8(String resource)
  3. openInputStream(String resourceString, ClassLoader classLoader)
  4. parseASX(String inputResource)
  5. printUsage(ResourceBundle bundle)
  6. resourceExists(String s)
  7. runtimeResourceLocation(String src)
  8. sanitizeResource(String inputResource)
  9. toFile(Class c, String resource)