Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

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

Usage

From source file:com.geozen.demo.foursquare.jiramot.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from   w  w  w .j a va  2  s.  c  o  m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " GeoZen");

    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.gmail.ferusgrim.util.UuidGrabber.java

public Map<String, UUID> call() throws Exception {
    JSONParser jsonParser = new JSONParser();
    Map<String, UUID> responseMap = new HashMap<String, UUID>();

    URL url = new URL("https://api.mojang.com/profiles/minecraft");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);//from  w  w w  . j av  a  2s .c om
    connection.setDoInput(true);
    connection.setDoOutput(true);

    String body = JSONArray.toJSONString(this.namesToLookup);

    OutputStream stream = connection.getOutputStream();
    stream.write(body.getBytes());
    stream.flush();
    stream.close();

    JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));

    for (Object profile : array) {
        JSONObject jsonProfile = (JSONObject) profile;
        String id = (String) jsonProfile.get("id");
        String name = (String) jsonProfile.get("name");
        UUID uuid = Grab.uuidFromResult(id);
        responseMap.put(name, uuid);
    }

    return responseMap;
}

From source file:io.wittmann.jiralist.servlet.ProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  www  .  j ava2  s .c o m*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    long requestId = requestCounter++;

    String proxyTo = "https://issues.jboss.org/rest/api/2";
    if (req.getHeader("X-Proxy-To") != null) {
        proxyTo = req.getHeader("X-Proxy-To");
    }
    String url = proxyTo + req.getPathInfo();
    if (req.getQueryString() != null) {
        url += "?" + req.getQueryString();
    }

    System.out.println("[" + requestId + "]: Proxying to: " + url);
    boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put");

    URL remoteUrl = new URL(url);
    HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection();
    if (isWrite) {
        remoteConn.setDoOutput(true);
    }
    remoteConn.setRequestMethod(req.getMethod());

    String auth = req.getHeader("Authorization");
    if (auth != null) {
        remoteConn.setRequestProperty("Authorization", auth);
    }
    String ct = req.getHeader("Content-Type");
    if (ct != null) {
        remoteConn.setRequestProperty("Content-Type", ct);
    }
    String cl = req.getHeader("Content-Length");
    if (cl != null) {
        remoteConn.setRequestProperty("Content-Length", cl);
    }
    String accept = req.getHeader("Accept");
    if (accept != null) {
        remoteConn.setRequestProperty("Accept", accept);
    }

    System.out.println("[" + requestId + "]: Request Info:");
    System.out.println("[" + requestId + "]:     Method: " + req.getMethod());
    System.out.println("[" + requestId + "]:     Has auth:   " + (auth != null));
    System.out.println("[" + requestId + "]:     Content-Type: " + ct);
    System.out.println("[" + requestId + "]:     Content-Length: " + cl);

    if (isWrite) {
        InputStream requestIS = null;
        OutputStream remoteOS = null;
        try {
            requestIS = req.getInputStream();
            remoteOS = remoteConn.getOutputStream();
            IOUtils.copy(requestIS, remoteOS);
            remoteOS.flush();
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(500, e.getMessage());
            return;
        } finally {
            IOUtils.closeQuietly(requestIS);
            IOUtils.closeQuietly(remoteOS);
        }
    }

    InputStream remoteIS = null;
    OutputStream responseOS = null;
    int responseCode = remoteConn.getResponseCode();

    System.out.println("[" + requestId + "]: Response Info:");
    System.out.println("[" + requestId + "]:     Code: " + responseCode);

    if (responseCode == 400) {
        remoteIS = remoteConn.getInputStream();
        responseOS = System.out;
        IOUtils.copy(remoteIS, responseOS);
        IOUtils.closeQuietly(remoteIS);
        resp.sendError(400, "Error 400");
    } else {
        try {
            Map<String, List<String>> headerFields = remoteConn.getHeaderFields();
            for (String headerName : headerFields.keySet()) {
                if (headerName == null) {
                    continue;
                }
                if (EXCLUDE_HEADERS.contains(headerName)) {
                    continue;
                }
                String headerValue = remoteConn.getHeaderField(headerName);
                resp.setHeader(headerName, headerValue);
                System.out.println("[" + requestId + "]:     " + headerName + " : " + headerValue);
            }
            resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$
            remoteIS = remoteConn.getInputStream();
            responseOS = resp.getOutputStream();
            int bytesCopied = IOUtils.copy(remoteIS, responseOS);
            System.out.println("[" + requestId + "]:     Bytes Proxied: " + bytesCopied);
            resp.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(500, e.getMessage());
        } finally {
            IOUtils.closeQuietly(responseOS);
            IOUtils.closeQuietly(remoteIS);
        }
    }
}

From source file:jp.go.nict.langrid.commons.protobufrpc.URLRpcChannel.java

public void call(BlockPE<OutputStream, IOException> sender, BlockPE<InputStream, IOException> successReceiver,
        BlockPPE<InputStream, IOException, IOException> failReceiver) {
    HttpURLConnection c = null;
    try {/*  w  w  w . j  av a  2 s  .c  o  m*/
        c = (HttpURLConnection) url.openConnection();
        c.setDoOutput(true);
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            c.addRequestProperty(entry.getKey(), entry.getValue());
        }
        if (!requestProperties.containsKey(LangridConstants.HTTPHEADER_PROTOCOL)) {
            c.addRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.PROTOBUF_RPC);
        }
        if (System.getProperty("http.proxyHost") != null) {
            String proxyAuthUser = System.getProperty("http.proxyUser");
            if (proxyAuthUser != null) {
                String proxyAuthPass = System.getProperty("http.proxyPassword");
                String header = proxyAuthUser + ":" + ((proxyAuthPass != null) ? proxyAuthPass : "");
                c.setRequestProperty("Proxy-Authorization",
                        "Basic " + new String(Base64.encodeBase64(header.getBytes())));
            }
        }
        if (authUserName != null && authUserName.length() > 0) {
            String header = authUserName + ":" + ((authPassword != null) ? authPassword : "");
            c.setRequestProperty("Authorization",
                    "Basic " + new String(Base64.encodeBase64(header.getBytes())));
        }
        OutputStream os = c.getOutputStream();
        try {
            sender.execute(os);
        } finally {
            os.close();
        }
        for (Map.Entry<String, List<String>> entry : c.getHeaderFields().entrySet()) {
            responseProperties.put(entry.getKey(),
                    StringUtil.join(entry.getValue().toArray(ArrayUtil.emptyStrings()), ", "));
        }
        InputStream is = c.getInputStream();
        try {
            successReceiver.execute(is);
        } finally {
            is.close();
        }
    } catch (IOException e) {
        InputStream es = null;
        if (c != null) {
            es = c.getErrorStream();
        }
        try {
            failReceiver.execute(es, e);
        } catch (IOException ee) {
        } finally {
            if (es != null) {
                try {
                    es.close();
                } catch (IOException ee) {
                }
            }
        }

    }
}

From source file:com.scm.reader.livescanner.search.SearchRequestBuilder.java

public String query(Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    this.responseStatus = -1;
    this.responseBody = null;
    String contentType = "multipart/form-data";

    byte[] image = data.getRequestContent();
    byte[] requestBody = createMultipartRequest(image, params);
    final String dateStr = data.getFormattedDate();

    HttpURLConnection conn = (HttpURLConnection) (new URL(getQueryUrl())).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);//from   w  w  w  . j  a  v  a2  s . c  om

    conn.setRequestProperty("Content-Type", contentType + "; boundary=" + MULTIPART_BOUNDARY);
    //KA-sign auth
    conn.setRequestProperty("Authorization", getAuthorizationHeader(AUTHENTICATION_METHOD, "POST", requestBody,
            contentType, dateStr, KConfig.getConfig().getPath()));
    //Token auth
    //conn.setRequestProperty("Authorization", "Token " + SECRET_TOKEN);

    conn.setRequestProperty("Accept", "application/json; charset=utf-8");
    conn.setRequestProperty("Date", dateStr);

    System.out.println("REQUESTBODY: " + requestBody.toString());
    conn.getOutputStream().write(requestBody);
    return readHttpResponse(conn);
}

From source file:com.github.cambierr.jcollector.sender.OpenTsdbHttp.java

@Override
public void send(ConcurrentLinkedQueue<Metric> _metrics) throws IOException {

    JSONArray entries = toJson(_metrics);

    if (entries.length() == 0) {
        return;//from ww w.j ava  2  s . c  o  m
    }

    HttpURLConnection conn = (HttpURLConnection) host.openConnection();
    if (auth != null) {
        conn.setRequestProperty("Authorization", auth.getAuth());
    }

    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStream body = conn.getOutputStream();
    body.write(entries.toString().getBytes());
    body.flush();

    if (conn.getResponseCode() >= 400) {
        BufferedReader responseBody = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        String output;
        StringBuilder sb = new StringBuilder("Could not push data to OpenTSDB through ")
                .append(getClass().getSimpleName()).append("\n");
        while ((output = responseBody.readLine()) != null) {
            sb.append(output).append("\n");
        }
        Worker.logger.log(Level.WARNING, sb.toString());
        throw new IOException(conn.getResponseMessage() + " (" + conn.getResponseCode() + ")");
    }
}

From source file:io.github.retz.web.WebConsoleTest.java

@Test
public void ping() throws IOException {
    URL url = new URL("http://localhost:24301/ping");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoOutput(true);
    StringWriter writer = new StringWriter();
    IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
    assert "OK".equals(writer.toString());
}

From source file:org.digitalcampus.oppia.task.DownloadMediaTask.java

@Override
protected Payload doInBackground(Payload... params) {
    Payload payload = params[0];/*from   w  w w.  j a  va  2  s  . c o m*/
    for (Object o : payload.getData()) {
        Media m = (Media) o;
        File file = new File(MobileLearning.MEDIA_PATH, m.getFilename());
        try {

            URL u = new URL(m.getDownloadUrl());
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            c.setConnectTimeout(
                    Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
                            ctx.getString(R.string.prefServerTimeoutConnection))));
            c.setReadTimeout(
                    Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
                            ctx.getString(R.string.prefServerTimeoutResponse))));

            int fileLength = c.getContentLength();

            DownloadProgress dp = new DownloadProgress();
            dp.setMessage(m.getFilename());
            dp.setProgress(0);
            publishProgress(dp);

            FileOutputStream f = new FileOutputStream(file);
            InputStream in = c.getInputStream();

            MessageDigest md = MessageDigest.getInstance("MD5");
            in = new DigestInputStream(in, md);

            byte[] buffer = new byte[8192];
            int len1 = 0;
            long total = 0;
            int progress = 0;
            while ((len1 = in.read(buffer)) > 0) {
                total += len1;
                progress = (int) (total * 100) / fileLength;
                if (progress > 0) {
                    dp.setProgress(progress);
                    publishProgress(dp);
                }
                f.write(buffer, 0, len1);
            }
            f.close();

            dp.setProgress(100);
            publishProgress(dp);

            // check the file digest matches, otherwise delete the file 
            // (it's either been a corrupted download or it's the wrong file)
            byte[] digest = md.digest();
            String resultMD5 = "";

            for (int i = 0; i < digest.length; i++) {
                resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
            }

            Log.d(TAG, "supplied   digest: " + m.getDigest());
            Log.d(TAG, "calculated digest: " + resultMD5);

            if (!resultMD5.contains(m.getDigest())) {
                this.deleteFile(file);
                payload.setResult(false);
                payload.setResultResponse(ctx.getString(R.string.error_media_download));
            } else {
                payload.setResult(true);
                payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename()));
            }
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
            payload.setResult(false);
            payload.setResultResponse(ctx.getString(R.string.error_media_download));
        } catch (IOException e1) {
            e1.printStackTrace();
            this.deleteFile(file);
            payload.setResult(false);
            payload.setResultResponse(ctx.getString(R.string.error_media_download));
        } catch (NoSuchAlgorithmException e) {
            if (!MobileLearning.DEVELOPER_MODE) {
                BugSenseHandler.sendException(e);
            } else {
                e.printStackTrace();
            }
            payload.setResult(false);
            payload.setResultResponse(ctx.getString(R.string.error_media_download));
        }
    }
    return payload;
}

From source file:com.cacacan.sender.GcmSenderRunnable.java

@Override
public void run() {
    LOGGER.info("Started sender thread");
    try {/*from   www .  j  a  va  2  s . co m*/
        // Prepare JSON containing the GCM message content. What to send and
        // where to send.
        final JSONObject jGcmData = new JSONObject();
        final JSONObject jData = new JSONObject();
        jData.put("message", message.trim());
        // Where to send GCM message.
        jGcmData.put("to", "/topics/global");

        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        final URL url = new URL("https://android.googleapis.com/gcm/send");
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        final OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());
        LOGGER.info("Sent message via GCM: " + message);
        // Read GCM response.
        final InputStream inputStream = conn.getInputStream();
        final String resp = IOUtils.toString(inputStream);
        LOGGER.info(resp);
    } catch (IOException | JSONException e) {
        LOGGER.error(
                "Unable to send GCM message.\n" + "Please ensure that API_KEY has been replaced by the server "
                        + "API key, and that the device's registration token is correct (if specified).");
    }
}

From source file:com.opensesame.opensesamedoor.GCMSender.GcmSender.java

@Override
protected Long doInBackground(String... params) {
    String message = params[0];/*from w w  w  .j av a 2s . co  m*/
    String deviceToken = params[1];
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", message.trim());
        // Where to send GCM message.
        if (deviceToken != null) {
            jGcmData.put("to", deviceToken.trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return 1L;
}