Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

In this page you can find the example usage for java.net HttpURLConnection 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:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Opens a GET connection.//from   w  w  w .j  a v a 2s . c o m
 *
 * @param url The URL to connect to.
 *
 * @return A GET connection to this URL.
 * @throws IOException If an exception occurred while contacting the server.
 */
static private HttpURLConnection getGETConnection(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    return connection;
}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Retrieves a JSON object from the specified URL.
 * <p/>//from  www .  j  ava2 s. c o m
 * Note that this is a blocking method; it should not be called from the URI thread.
 *
 * @param urlString The URL to retrieve the JSON from.
 * @return The JSON object at the specified URL.
 * @throws IOException   if a connection to the server could not be established.
 * @throws JSONException if the server did not return valid JSON.
 */
public static JSONObject getJson(String urlString) throws IOException, JSONException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(10000);
    connection.setConnectTimeout(15000);
    connection.setRequestMethod("GET");
    connection.setDoInput(true);
    connection.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    StringBuilder data = new StringBuilder();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        data.append(line);
        data.append(newLine);
    }
    reader.close();

    return new JSONObject(data.toString());
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?url/*  w  w w.ja va  2s.c o m*/
 *
 * @param inputStream ?
 * @param fileName    ??
 * @param fileType    
 * @param contentType 
 * @param identity    
 * @return 
 */
public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName,
        String fileType, String contentType, String identity) {
    String lineEnd = System.getProperty("line.separator");
    String twoHyphens = "--";
    String boundary = "*****";
    String result = null;
    try {
        //?
        URL submit = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) submit.openConnection();
        //
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        //?
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", DEFAULT_CHARSET);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //??
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName
                + ";Content-Type=\"" + contentType + lineEnd);
        dos.writeBytes(lineEnd);

        byte[] buffer = new byte[8192]; // 8k
        int count = 0;
        while ((count = inputStream.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        inputStream.close(); //?
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();

        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET);
        BufferedReader br = new BufferedReader(isr);
        result = br.readLine();
        dos.close();
        is.close();
    } catch (IOException e) {
        logger.error("", e);
    }
    return result;
}

From source file:com.book.jtm.chap03.HttpClientDemo.java

public static void sendRequest(String method, String url) throws IOException {
    InputStream is = null;/* www  .  ja va  2s.co  m*/
    try {
        URL newUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection();
        // ?10
        conn.setReadTimeout(10000);
        // 15
        conn.setConnectTimeout(15000);
        // ?,GET"GET",post"POST"
        conn.setRequestMethod("GET");
        // ??
        conn.setDoInput(true);
        // ??,????
        conn.setDoOutput(true);
        // Header
        conn.setRequestProperty("Connection", "Keep-Alive");
        // ?
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsList.add(new BasicNameValuePair("username", "mr.simple"));
        paramsList.add(new BasicNameValuePair("pwd", "mypwd"));
        writeParams(conn.getOutputStream(), paramsList);

        // ?
        conn.connect();
        is = conn.getInputStream();
        // ?
        String result = convertStreamToString(is);
        Log.i("", "###  : " + result);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.zf.util.Post_NetNew.java

/**
 * ?/*from www  .j  a v  a  2 s.c o m*/
 * 
 * @param pams
 * @param ip
 * @param port
 * @return
 * @throws Exception
 */
public static String pn(Map<String, String> pams, String ip, int port) throws Exception {
    if (null == pams) {
        return "";
    }
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Type.HTTP, addr);
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy);
    httpConn.setConnectTimeout(30000);
    httpConn.setReadTimeout(30000);
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}

From source file:com.newrelic.agent.Deployments.java

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {//w w w .  j a v  a 2s . c  om
    /*  39: 35 */ String appName = config.getApplicationName();
    /*  40: 36 */ if (cmd.hasOption("appname")) {
        /*  41: 37 */ appName = cmd.getOptionValue("appname");
        /*  42:    */ }
    /*  43: 39 */ if (appName == null) {
        /*  44: 40 */ throw new IllegalArgumentException(
                "A deployment must be associated with an application.  Set app_name in newrelic.yml or specify the application name with the -appname switch.");
        /*  45:    */ }
    /*  46: 43 */ System.out.println("Recording a deployment for application " + appName);
    /*  47:    */
    /*  48: 45 */ String uri = "/deployments.xml";
    /*  49: 46 */ String payload = getDeploymentPayload(appName, cmd);
    /*  50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : "");
    /*  51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri);
    /*  52:    */
    /*  53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}",
            new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) }));
    /*  54:    */
    /*  55:    */
    /*  56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    /*  57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey());
    /*  58:    */
    /*  59: 56 */ conn.setRequestMethod("POST");
    /*  60: 57 */ conn.setConnectTimeout(10000);
    /*  61: 58 */ conn.setReadTimeout(10000);
    /*  62: 59 */ conn.setDoOutput(true);
    /*  63: 60 */ conn.setDoInput(true);
    /*  64:    */
    /*  65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length()));
    /*  66: 63 */ conn.setFixedLengthStreamingMode(payload.length());
    /*  67: 64 */ conn.getOutputStream().write(payload.getBytes());
    /*  68:    */
    /*  69: 66 */ int responseCode = conn.getResponseCode();
    /*  70: 67 */ if (responseCode < 300)
    /*  71:    */ {
        /*  72: 68 */ System.out.println("Deployment successfully recorded");
        /*  73:    */ }
    /*  74: 69 */ else if (responseCode == 401)
    /*  75:    */ {
        /*  76: 70 */ System.out.println(
                "Unable to notify New Relic of the deployment because of an authorization error.  Check your license key.");
        /*  77: 71 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  78:    */ }
    /*  79:    */ else
    /*  80:    */ {
        /*  81: 73 */ System.out.println("Unable to notify New Relic of the deployment");
        /*  82: 74 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  83:    */ }
    /*  84: 76 */ boolean isError = responseCode >= 300;
    /*  85: 77 */ if ((isError) || (config.isDebugEnabled()))
    /*  86:    */ {
        /*  87: 78 */ System.out.println("Response code: " + responseCode);
        /*  88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream();
        /*  89: 81 */ if (inStream != null)
        /*  90:    */ {
            /*  91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /*  92: 83 */ Streams.copy(inStream, output);
            /*  93:    */
            /*  94: 85 */ PrintStream out = isError ? System.err : System.out;
            /*  95:    */
            /*  96: 87 */ out.println(output);
            /*  97:    */ }
        /*  98:    */ }
    /*  99: 90 */ return responseCode;
    /* 100:    */ }

From source file:com.onesignal.OneSignalRestClient.java

private static void makeRequest(String url, String method, JSONObject jsonBody,
        ResponseHandler responseHandler) {
    HttpURLConnection con = null;
    int httpResponse = -1;
    String json = null;//from   w  ww.j  av  a2s  .  c om

    try {
        con = (HttpURLConnection) new URL(BASE_URL + url).openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);

        if (jsonBody != null)
            con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(method);

        if (jsonBody != null) {
            String strJsonBody = jsonBody.toString();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody);

            byte[] sendBytes = strJsonBody.getBytes("UTF-8");
            con.setFixedLengthStreamingMode(sendBytes.length);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sendBytes);
        }

        httpResponse = con.getResponseCode();

        InputStream inputStream;
        Scanner scanner;
        if (httpResponse == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
            scanner = new Scanner(inputStream, "UTF-8");
            json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
            scanner.close();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json);

            if (responseHandler != null)
                responseHandler.onSuccess(json);
        } else {
            inputStream = con.getErrorStream();
            if (inputStream == null)
                inputStream = con.getInputStream();

            if (inputStream != null) {
                scanner = new Scanner(inputStream, "UTF-8");
                json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                scanner.close();
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json);
            } else
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN,
                        method + " HTTP Code: " + httpResponse + " No response body!");

            if (responseHandler != null)
                responseHandler.onFailure(httpResponse, json, null);
        }
    } catch (Throwable t) {
        if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException)
            OneSignal.Log(OneSignal.LOG_LEVEL.INFO,
                    "Could not send last request, device is offline. Throwable: " + t.getClass().getName());
        else
            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t);

        if (responseHandler != null)
            responseHandler.onFailure(httpResponse, null, t);
    } finally {
        if (con != null)
            con.disconnect();
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Http/*w  ww  .j a  va2  s.  c  om*/
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param outputJson    ?
 * @return 
 */
public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}

From source file:LNISmokeTest.java

/**
 * Get an item with WebDAV GET http request.
 * //from www.ja  va  2s.com
 * @param lni the lni
 * @param itemHandle the item handle
 * @param packager the packager
 * @param output the output
 * @param endpoint the endpoint
 * 
 * @throws RemoteException the remote exception
 * @throws ProtocolException the protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String itemURI = doLookup(lni, itemHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager);
    System.err.println("DEBUG: GET from URL: " + url.toString());

    // connect with GET method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    fixBasicAuth(url, conn);
    conn.connect();
    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    InputStream in = conn.getInputStream();
    OutputStream out = new FileOutputStream(output);
    copyStream(in, out);
    in.close();
    out.close();

    System.err.println("DEBUG: Created local file " + output);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
}

From source file:io.jari.geenstijl.API.API.java

public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin)
        throws IOException {
    HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
    http.setRequestMethod("POST");
    http.setDoInput(true);
    http.setDoOutput(true);//ww  w .j a va  2 s  .c o  m
    if (cheader != null)
        http.setRequestProperty("Cookie", cheader);
    if (refererandorigin) {
        http.setRequestProperty("Referer",
                "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html");
        http.setRequestProperty("Origin", "http://www.geenstijl.nl");
    }
    OutputStream os = http.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    http.connect();

    InputStream in = http.getInputStream();
    String encoding = http.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        baos.write(buf, 0, len);
    }
    return new String(baos.toByteArray(), encoding);
}