Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.wso2.carbon.connector.integration.test.util.ConnectorIntegrationUtil.java

public static OMElement sendXMLRequest(String addUrl, String query)
        throws MalformedURLException, IOException, XMLStreamException {
    String charset = "UTF-8";
    System.out.println("=======url======" + addUrl + "=======" + query);
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);/*w  w  w. ja v  a  2 s  . co  m*/
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "text/xml;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }

    HttpURLConnection httpConn = (HttpURLConnection) connection;
    InputStream response;

    if (httpConn.getResponseCode() >= 400) {
        response = httpConn.getErrorStream();
    } else {
        response = connection.getInputStream();
    }

    String out = "{}";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }

        if (!sb.toString().trim().isEmpty()) {
            out = sb.toString();
        }
    }
    System.out.println("=======out======" + out);
    OMElement omElement = AXIOMUtil.stringToOM(out);
    return omElement;
}

From source file:org.kootox.episodesmanager.services.WebHelper.java

/**
 *
 * Download a file from the internet/*from   w  ww  .j  a va  2  s .c  o  m*/
 *
 * @param destinationDirectory the directory where the file will be saved
 * @param destinationFileName the name under which the file is saved
 * @param source the url from which to download the file
 */
public static void downloadFile(File destinationDirectory, String destinationFileName, URL source) {

    FileOutputStream out = null;
    InputStream in = null;

    try {
        URLConnection conn = source.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("content-type", "binary/data");
        in = conn.getInputStream();

        File destinationFile = new File(destinationDirectory, destinationFileName);
        out = new FileOutputStream(destinationFile);

        byte[] b = new byte[1024];
        int count;

        while ((count = in.read(b)) >= 0) {
            out.write(b, 0, count);
        }

    } catch (IOException eee) {
        log.error("Could not download file ", eee);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException eee) {
            log.debug("Could not close stream", eee);
        }
    }

}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static ImageLabel getImage(int id, String name) {
    try {/*from   w  ww  .  j a  va 2 s  .  co  m*/
        // logic for user verification

        //      Client client = ClientBuilder.newBuilder().newClient();
        //            WebTarget target = client.target("http://94.156.77.61:8080/photoshare");
        //            target = target.path("rest/image/getfile/MiltonStapler.jpg");
        //
        //            Invocation.Builder builder = target.request();
        //            Response response = builder.get();
        //            FileInputStream book = builder.get(FileInputStream.class);
        //            System.out.println("done");
        ProjectProperties props = new ProjectProperties();
        String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image/getfile/" + name;
        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();
        //            InputStreamReader isr = new InputStreamReader(is);
        //            
        //            int numCharsRead;
        //            char[] charArray = new char[1024];
        //            StringBuffer sb = new StringBuffer();
        //            while ((numCharsRead = isr.read(charArray)) > 0) {
        //                sb.append(charArray, 0, numCharsRead);
        //            }
        //            String result = sb.toString();
        BufferedImage bi = ImageIO.read(is);
        ImageLabel img = new ImageLabel(bi, id, name);
        return img;

        //            System.out.println("*** BEGIN ***");
        //            System.out.println(result);
        //            System.out.println("*** END ***");
    } catch (MalformedURLException ex) {
        Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:sh.isaac.provider.sync.git.gitblit.utils.ConnectionUtils.java

/**
 * Set authorization./*  w  ww . j  av a2  s  . c om*/
 *
 * @param conn the conn
 * @param username the username
 * @param password the password
 */
public static void setAuthorization(URLConnection conn, String username, char[] password) {
    if (!StringUtils.isEmpty(username) && ((password != null) && (password.length > 0))) {
        conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(
                toBytes(ArrayUtils.addAll(new String(username + ":").toCharArray(), password))));
    }
}

From source file:networkedassets.Useful.java

public static JSONObject readJsonFromUrl(String urlString, String username, String password)
        throws IOException, JSONException {

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (username.length() > 0 && password.length() > 0) {
        String encoded = Base64.encodeToString((username + ":" + password).getBytes(), false);
        conn.setRequestProperty("Authorization", "Basic " + encoded);
    }/*  w  w  w.  j  a  va2 s .co m*/

    InputStream is = conn.getInputStream();

    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static ArrayList<ImageLabel> getImages() {
    ProjectProperties props = new ProjectProperties();
    String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image";
    URL url;//  w w  w .  ja  v  a 2s.  c  o  m
    try {
        url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
        Gson gson = new Gson();

        RemoteImage[] remoteImages = gson.fromJson(result, RemoteImage[].class);

        ArrayList<ImageLabel> images = new ArrayList<ImageLabel>();
        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        for (RemoteImage rimg : remoteImages) {
            ImageLabel img = getImage(rimg.id, rimg.fileName);
            int imageWidth = img.getImage().getWidth(null);
            int imageHeight = img.getImage().getHeight(null);
            // just a relative estimation
            int imagesPerColumn = (int) Math.floor(Math.sqrt(Pagination.getImagesPerPage()));
            double ratio = (screenSize.height / (double) imageHeight < screenSize.width / (double) imageWidth)
                    ? screenSize.height / (double) imageHeight
                    : screenSize.width / (double) imageWidth;
            ratio = ratio / imagesPerColumn; // reduce ratio because more than 1 image are located in the column
            int resizeWidth = (int) (imageWidth * ratio);
            int resizeHeight = (int) (imageHeight * ratio);
            Image resizedImage = createResizedCopy(img.getImage(), resizeWidth, resizeHeight, false);
            images.add(new ImageLabel(resizedImage, img.getImageId(), img.getFileName()));
        }
        return images;
    } catch (MalformedURLException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }

    return null;
}

From source file:com.hazelcast.qasonar.utils.Utils.java

private static InputStream getBaseAuthInputStreamFromURL(String query, String basicAuthString)
        throws IOException {
    URL url = new URL(query);

    URLConnection uc = url.openConnection();
    uc.setRequestProperty("Authorization", basicAuthString);

    return uc.getInputStream();
}

From source file:com.agc.tmdb.Util.URLFetcher.java

/**
 * This is used to open a connection, Proxy details will be considered if provided.
 * @param url//from ww w  .j  ava  2s  . c om
 * @return
 * @throws TMDbException
 */
public static URLConnection openConnection(URL url) throws TMDbException {
    try {
        if (proxyHost != null) {
            System.getProperties().put("proxySet", "true");
            System.getProperties().put("proxyHost", proxyHost);
            System.getProperties().put("proxyPort", proxyPort);
        }

        URLConnection cnx = url.openConnection();

        if (proxyUsername != null) {
            cnx.setRequestProperty("Proxy-Authorization", proxyEncodedPassword);
        }

        return cnx;
    } catch (IOException ex) {
        throw new TMDbException(TMDbExceptionTypes.EXCEPTION_INVALID_URL, null, ex);
    }
}

From source file:de.akquinet.android.androlog.reporter.PostReporter.java

/**
 * Executes the given request as a HTTP POST action.
 *
 * @param url//from w w w . ja va2s.  com
 *            the url
 * @param params
 *            the parameter
 * @return the response as a String.
 * @throws IOException
 *             if the server cannot be reached
 */
public static void post(URL url, String params) throws IOException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpURLConnection) {
        ((HttpURLConnection) conn).setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
    }
    OutputStreamWriter writer = null;
    try {
        conn.setDoOutput(true);
        writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8"));
        // write parameters
        writer.write(params);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:org.pentaho.supportutility.rest.client.RestFulClient.java

/**
 * to call restful service to get license and data-source details
 * //from  w w  w.ja va2 s  .  c om
 * @param server
 * @param required
 * @param prop
 * @param webXml
 * @return
 */
public static String restFulService(String server, String required, final Properties prop, String webXml) {

    String outPut = null;
    String qualifiedUrl = null;
    // based on server get restful url
    if (server.equalsIgnoreCase(RestFulURL.BI_SERVER)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_BISERVER_URL);
    } else if (server.equalsIgnoreCase(RestFulURL.DI_SERVER)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_DISERVER_URL);
    } else if (server.equalsIgnoreCase(RestFulURL.SPOON_IDE)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_DISERVER_URL);
    }
    URL url = null;

    try {
        if (required.equalsIgnoreCase(RestFulURL.LICENSE)) {

            url = getLicenseUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.ANALYSIS)) {

            url = getAnalysisUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.METADATA)) {

            url = getMateDataUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.DSW)) {

            url = getDSW(qualifiedUrl);
        }

        // authenticating the restful service
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prop.getProperty(RestFulURL.USER_NAME),
                        prop.getProperty(RestFulURL.USER_PASSWORD).toCharArray());
            }

        });

        String basicAuth = RestFulURL.BASIC
                + new String(Base64.encodeBase64((prop.getProperty(RestFulURL.USER_NAME) + RestFulURL.COLON
                        + prop.getProperty(RestFulURL.USER_PASSWORD)).getBytes()));

        if (url != null) {
            // calling restful service
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection conn = (HttpURLConnection) urlConnection;
            urlConnection.setRequestProperty(RestFulURL.AUTHOR, basicAuth);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                outPut = br.readLine();
            }

            conn.disconnect();
        }

    } catch (MalformedURLException e) {
        e.getMessage();
    } catch (IOException e) {
        e.getMessage();
    }

    return outPut;

}