Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:org.spoutcraft.launcher.api.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*  w w  w  .  j a va  2  s . co m*/
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        result = Result.FAILURE;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:dlauncher.dialogs.Login.java

private void login_write(String UserName, String Password) {
    Logger.getGlobal().info("Started login process");
    Logger.getGlobal().info("Writing login data..");
    try {/*w ww  .  ja v a2s  . c o  m*/
        url = new URL("http://authserver.mojang.com/authenticate");

        final URLConnection con = url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json");
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()))) {
            writer.write("{\n" + "  \"agent\": {" + "    \"name\": \"Minecraft\"," + "    \"version\": 1" + "\n"
                    + "  },\n" + "  \"username\": \"" + UserName + "\",\n" + "\n" + "  \"password\": \""
                    + Password + "\",\n" + "}");

            writer.close();
        }
        Logger.getGlobal().info("Succesful written login data");
    } catch (MalformedURLException ex) {
        Logger.getGlobal().warning("Failed Writing login data,");
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex);
    } catch (IOException ex) {
        Logger.getGlobal().warning("Failed Writing login data,");
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex);
    }
}

From source file:org.spoutcraft.launcher.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/* w w w .  ja  v  a  2s.  co m*/
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java

private HttpURLConnection openSkinConnection(String uuid) throws IOException {
    URL url = new URL(SKIN_ADDR + uuid + "?unsigned=false");
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setReadTimeout(READ_TIMEOUT);
    connection.setDoInput(true);
    connection.setUseCaches(false);//from ww  w. ja va2 s  .c  o  m
    return (HttpURLConnection) connection;
}

From source file:org.jlibrary.core.http.client.HTTPDelegate.java

/**
 * Excecutes a void request/*from  w  w  w. j av a  2s  .  c  o m*/
 * 
 * @param methodName Name of the method to execute
 * @param params Method params
 * @param returnClass Class for the return object. If the class is InputStream this method will return 
 * the HTTP request input stream
 * @param inputStream Stream for reading contents that will be sent
 * 
 * @throws Exception If there is any problem running the request
 */
public Object doRequest(String methodName, Object[] params, Class returnClass, InputStream inputStream)
        throws Exception {

    try {
        logger.debug(servletURL.toString());
        logger.debug("opening connection");
        URLConnection conn = servletURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "text/plain");

        //write request and params:
        OutputStream stream = conn.getOutputStream();
        // write streaming header if necessary
        if (inputStream != null) {
            stream.write(ByteUtils.intToByteArray("stream-input".getBytes().length));
            stream.write("stream-input".getBytes());
            stream.flush();
        }
        if (returnClass == InputStream.class) {
            stream.write(ByteUtils.intToByteArray("stream-output".getBytes().length));
            stream.write("stream-output".getBytes());
            stream.flush();
        }

        // Write method
        stream.write(ByteUtils.intToByteArray(methodName.getBytes().length));
        stream.write(methodName.getBytes());
        //stream.flush();
        // Write parameters
        stream.write(ByteUtils.intToByteArray(params.length));
        for (int i = 0; i < params.length; i++) {
            byte[] content = SerializationUtils.serialize((Serializable) params[i]);
            stream.write(ByteUtils.intToByteArray(content.length));
            stream.write(content);
            stream.flush();
        }

        if (inputStream != null) {
            IOUtils.copy(inputStream, stream);
        }

        //stream.flush();
        //stream.close();

        //read response:
        InputStream input = conn.getInputStream();
        if (returnClass == InputStream.class) {
            // Contents will be read from outside
            return input;
        }
        ObjectInputStream objInput = new ObjectInputStream(input);
        Object o = objInput.readObject();
        if (o == null) {
            return null;
        }
        stream.close();
        if (o instanceof Exception) {
            throw (Exception) o;
        } else {
            if (returnClass == null) {
                return null;
            }
            // try to cast
            try {
                returnClass.cast(o);
            } catch (ClassCastException cce) {
                String msg = "Unexpected response from execution servlet: " + o;
                logger.error(msg);
                throw new Exception(msg);
            }
        }
        return o;
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    } catch (ClassCastException e) {
        throw new Exception(e);
    } catch (IOException e) {
        throw new Exception(e);
    }
}

From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java

private HttpURLConnection openNameToIdConnection() throws IOException {
    URL url = new URL(NAMES_TO_IDS_ADDR);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setReadTimeout(READ_TIMEOUT);
    connection.setDoInput(true);
    connection.setDoOutput(true);//from w  ww.j av  a  2 s .co m
    connection.setUseCaches(false);
    return (HttpURLConnection) connection;
}

From source file:com.wavemaker.runtime.ws.SyndFeedService.java

/**
 * Reads from the InputStream of the specified URL and builds the feed object from the returned XML.
 * //from  www .  j a v a 2  s. c  om
 * @param feedURL The URL to read feed from.
 * @param httpBasicAuthUsername The username for HTTP Basic Authentication.
 * @param httpBasicAuthPassword The password for HTTP Basic Authentication.
 * @param connectionTimeout HTTP connection timeout.
 * @return A feed object.
 */
@ExposeToClient
public Feed getFeedWithHttpConfig(String feedURL, String httpBasicAuthUsername, String httpBasicAuthPassword,
        int connectionTimeout) {
    URL url = null;
    try {
        url = new URL(feedURL);
    } catch (MalformedURLException e) {
        throw new WebServiceInvocationException(e);
    }

    SyndFeedInput input = new SyndFeedInput();
    try {
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof HttpURLConnection) {
            urlConn.setAllowUserInteraction(false);
            urlConn.setDoInput(true);
            urlConn.setDoOutput(false);
            ((HttpURLConnection) urlConn).setInstanceFollowRedirects(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty(USER_AGENT_KEY, USER_AGENT_VALUE);

            urlConn.setConnectTimeout(connectionTimeout);

            if (httpBasicAuthUsername != null && httpBasicAuthUsername.length() > 0) {
                String auth = httpBasicAuthPassword == null ? httpBasicAuthUsername
                        : httpBasicAuthUsername + ":" + httpBasicAuthPassword;
                urlConn.setRequestProperty(BASIC_AUTH_KEY,
                        BASIC_AUTH_VALUE_PREFIX + Base64.encodeBase64URLSafeString(auth.getBytes()));
            }
        }
        SyndFeed feed = input.build(new XmlReader(urlConn));
        return FeedBuilder.getFeed(feed);
    } catch (IllegalArgumentException e) {
        throw new WebServiceInvocationException(e);
    } catch (FeedException e) {
        throw new WebServiceInvocationException(e);
    } catch (IOException e) {
        throw new WebServiceInvocationException(e);
    }
}

From source file:com.mcapanel.utils.ErrorHandler.java

private void e(String af) {
    try {// w  w  w . j  a  v a  2 s  .  c  om
        URLConnection kx = new URL(v.toString()).openConnection();

        kx.setDoOutput(true);
        kx.setDoInput(true);

        OutputStreamWriter qd = new OutputStreamWriter(kx.getOutputStream());

        qd.write(af);
        qd.flush();

        BufferedReader yx = new BufferedReader(new InputStreamReader(kx.getInputStream()));

        String lx = yx.readLine();

        if (lx != null) {
            JSONObject pg = (JSONObject) new JSONParser().parse(lx);

            if (pg.containsKey("v") && v(pg.get("v")).toString().equals(x.toString()))
                cd = true;
            else
                cd = false;

            if (pg != null && pg.containsKey(w.toString()) && pg.containsKey(b.toString())) {
                ObfuscatedString un = v(pg.get(b.toString()));
                ObfuscatedString lf = v(pg.get(w.toString()));

                if (lf.toString().equals(q.toString())) {
                    if (un.toString().equals(k.toString()) && pg.containsKey(c.toString())) {
                        g(v(pg.get(c.toString())));
                        e = true;
                    }
                } else if (lf.toString().equals(t.toString())) {
                    g(new ObfuscatedString(
                            new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
                    e = false;
                }
            } else
                throw new Exception();
        } else
            throw new Exception();

        qd.close();
        yx.close();
    } catch (Exception e1) {
        g(new ObfuscatedString(
                new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
        e = false;
    }
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

@SuppressWarnings("deprecation")
public String sendRequest(String payLoad, String authToken) {
    URLConnection conn = null;
    String strRet = null;/*from   ww w.j  a v  a2s.co m*/
    try {
        URL urlConn = new URL(payLoad);

        conn = null;
        conn = urlConn.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Accept", "application/json");

        DataInputStream dataIn = new DataInputStream(conn.getInputStream());
        String strChunk = "";
        StringBuilder sb = new StringBuilder("");
        while (null != ((strChunk = dataIn.readLine())))
            sb.append(strChunk);

        strRet = sb.toString();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("MalformedURLException in DSCommHandler");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException in DSCommHandler: " + conn.getHeaderField(0));
        //         e.printStackTrace();
    }
    return strRet;
}

From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

private HttpURLConnection createUrlConnection(String url) throws IOException {
    URL newURL = new URL(url);
    URLConnection urlConnection = newURL.openConnection();
    urlConnection.setConnectTimeout(mConfig.connTimeOut);
    urlConnection.setReadTimeout(mConfig.soTimeOut);
    urlConnection.setDoInput(true);
    urlConnection.setUseCaches(false);/*from   w ww .ja va 2s  . c o  m*/
    return (HttpURLConnection) urlConnection;
}