Example usage for java.net HttpURLConnection HTTP_MULT_CHOICE

List of usage examples for java.net HttpURLConnection HTTP_MULT_CHOICE

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_MULT_CHOICE.

Prototype

int HTTP_MULT_CHOICE

To view the source code for java.net HttpURLConnection HTTP_MULT_CHOICE.

Click Source Link

Document

HTTP Status-Code 300: Multiple Choices.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_MULT_CHOICE);
}

From source file:Main.java

public static URI unredirect(URI uri) throws IOException {
    if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
        return uri;
    }//from   w  w  w . j ava2  s.  c o  m
    URL url = uri.toURL();

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    connection.setDoInput(false);
    connection.setRequestMethod("HEAD");
    connection.setRequestProperty("User-Agent", "ZXing (Android)");
    try {
        connection.connect();
        switch (connection.getResponseCode()) {
        case HttpURLConnection.HTTP_MULT_CHOICE:
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
        case HttpURLConnection.HTTP_SEE_OTHER:
        case 307: // No constant for 307 Temporary Redirect ?
            String location = connection.getHeaderField("Location");
            if (location != null) {
                try {
                    return new URI(location);
                } catch (URISyntaxException e) {
                    // nevermind
                }
            }
        }
        return uri;
    } finally {
        connection.disconnect();
    }
}

From source file:de.intevation.irix.ImageClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param imageUrl The url to send the request to.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report.//from w  ww  .  j a va  2s .  co  m
 *
 * @throws IOException if communication with print service failed.
 * @throws ImageException if the print job failed.
 */
public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpGet get = new HttpGet(imageUrl);
    CloseableHttpResponse resp = client.execute(get);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new ImageException(new String(retval));
        } else {
            throw new ImageException("Communication with print service '" + imageUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./* ww  w  . j  a v  a  2  s.c  o  m*/
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Delete.java

@Override
public BufferedReader execute() {
    String uri = null;/*w  w  w.  j av  a  2  s .co  m*/

    //init check
    if (!Synergykit.isInit()) {

        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);
        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return null;
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Get.java

public InputStream halfExecute() {
    String uri = null;//from   w w  w  . j av  a 2s.co  m

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property
        httpURLConnection.addRequestProperty("Cache-Control", "max-stale=120");
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(true);
        httpURLConnection.setDefaultUseCaches(true);

        if (isAuthorizationEnabled()) {
            httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                    "Basic " + Base64.encodeToString(
                            (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                            Base64.NO_WRAP)); //set authorization
        }

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return httpURLConnection.getInputStream();
        } else {
            return httpURLConnection.getErrorStream();
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Post.java

@Override
public BufferedReader execute() {
    String jSon = null;/*from w ww.ja va2 s  . c o m*/
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();
        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Patch.java

@Override
public BufferedReader execute() {
    String jSon = null;//  w ww.  j  av  a2 s.  c o  m
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();

        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.PostFile.java

@Override
public BufferedReader execute() {
    String uri = null;//www.  j a v a 2s. c om

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
        httpURLConnection.addRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (data != null) {
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());

            dataOutputStream.writeBytes(TWO_HYPHENS + BOUNDARY + CRLF);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + ATTACHMENT_NAME
                    + "\";filename=\"" + ATTACHMENT_FILE_NAME + "\"" + CRLF);
            dataOutputStream.writeBytes(CRLF);
            dataOutputStream.write(data);
            dataOutputStream.writeBytes(CRLF);
            dataOutputStream.writeBytes(TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + CRLF);
            dataOutputStream.flush();
            dataOutputStream.close();
        }

        statusCode = httpURLConnection.getResponseCode(); //get status code
        SynergykitLog.print(Integer.toString(statusCode));

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:org.exoplatform.shareextension.service.UploadAction.java

@Override
protected boolean doExecute() {
    String id = uploadInfo.uploadId;
    String boundary = "----------------------------" + id;
    String CRLF = "\r\n";
    int status = -1;
    OutputStream output = null;/*  w  w w.jav  a 2s.  c o m*/
    PrintWriter writer = null;
    try {
        // Open a connection to the upload web service
        StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal")
                .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id);
        URL uploadUrl = new URL(stringUrl.toString());
        HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection();
        uploadReq.setDoOutput(true);
        uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        // Pass the session cookies for authentication
        CookieStore store = ExoConnectionUtils.cookiesStore;
        if (store != null) {
            StringBuffer cookieString = new StringBuffer();
            for (Cookie cookie : store.getCookies()) {
                cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
            }
            uploadReq.addRequestProperty("Cookie", cookieString.toString());
        }
        ExoConnectionUtils.setUserAgent(uploadReq);
        // Write the form data
        output = uploadReq.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                + uploadInfo.fileToUpload.documentName + "\"").append(CRLF);
        writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF);
        writer.append(CRLF).flush();
        byte[] buf = new byte[1024];
        while (uploadInfo.fileToUpload.documentData.read(buf) != -1) {
            output.write(buf);
        }
        output.flush();
        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF).flush();
        // Execute the connection and retrieve the status code
        status = uploadReq.getResponseCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e);
    } finally {
        if (uploadInfo != null && uploadInfo.fileToUpload != null
                && uploadInfo.fileToUpload.documentData != null)
            try {
                uploadInfo.fileToUpload.documentData.close();
            } catch (IOException e1) {
                Log.e(LOG_TAG, "Error while closing the upload stream", e1);
            }
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error while closing the connection", e);
            }
        if (writer != null)
            writer.close();
    }
    if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) {
        // Exit if the upload went wrong
        return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName);
    }
    status = -1;
    try {
        // Prepare the request to save the file in JCR
        String stringUrl = postInfo.ownerAccount.serverUrl + "/portal"
                + ExoConstants.DOCUMENT_CONTROL_PATH_REST;
        Uri moveUri = Uri.parse(stringUrl);
        moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id)
                .appendQueryParameter("action", "save")
                .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace)
                .appendQueryParameter("driveName", uploadInfo.drive)
                .appendQueryParameter("currentFolder", uploadInfo.folder)
                .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build();
        HttpGet moveReq = new HttpGet(moveUri.toString());
        // Execute the request and retrieve the status code
        HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq);
        status = move.getStatusLine().getStatusCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e);
    }
    boolean ret = false;
    if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
        ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully");
    } else {
        ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName);
    }
    return ret;
}