Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:net.mceoin.cominghome.api.NestUtil.java

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *//*from  w ww. ja v a 2 s.co m*/
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

    String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth="
            + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

            //                System.out.println("Redirect to URL : " + newUrl);

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    if (error) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

private void setSignatureLayout() {
    LayoutInflater dialogInflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    dialogView = dialogInflater.inflate(R.layout.dialog_signature, null);
    mSignaturePad = (SignaturePad) dialogView.findViewById(R.id.signature_pad);

    clearButton = (Button) dialogView.findViewById(R.id.clearButton);
    sendButton = (Button) dialogView.findViewById(R.id.sendButton);

    mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
        @Override//from   w w  w  . java  2s .c  om
        public void onSigned() {
            clearButton.setEnabled(true);
            sendButton.setEnabled(true);
        }

        @Override
        public void onClear() {
            clearButton.setEnabled(false);
            sendButton.setEnabled(false);
        }
    });
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSignaturePad.clear();
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //send sign image to server
            ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                private String num = Integer.toString(currentViewItem);

                @Override
                protected Boolean doInBackground(String... params) {
                    URL obj = null;
                    try {
                        obj = new URL("http://165.194.104.22:5000/enroll_sign");
                        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                        //implement below code if token is send to server
                        con = ConnectServer.getInstance().setHeader(con);

                        con.setDoOutput(true);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        signatureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] b = baos.toByteArray();
                        String sign_image = Base64.encodeToString(b, Base64.DEFAULT);
                        Log.d(TAG, "sign_image: " + sign_image.length());

                        String parameter = URLEncoder.encode("num", "UTF-8") + "="
                                + URLEncoder.encode(num, "UTF-8");
                        parameter += "&" + URLEncoder.encode("sign_image", "UTF-8") + "="
                                + URLEncoder.encode(sign_image, "UTF-8");

                        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                        wr.write(parameter);
                        wr.flush();

                        BufferedReader rd = null;

                        if (con.getResponseCode() == 200) {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

                            Log.d("---- success ----", rd.toString());

                        } else {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                            Log.d("---- failed ----", String.valueOf(rd.readLine()));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Boolean aBoolean) {

                }
            });
            ConnectServer.getInstance().execute();
            signature_dialog.dismiss();
            loadBoards();
        }
    });
}

From source file:org.jetbrains.webdemo.handlers.ServerHandler.java

private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> postParameters) {
    final boolean hasoutbody = (request.getMethod().equals("POST"));

    try {/*from w ww  . j a va2  s  . c  om*/
        final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/"
                + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        final Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            final String header = headers.nextElement();
            final Enumeration<String> values = request.getHeaders(header);
            while (values.hasMoreElements()) {
                final String value = values.nextElement();
                conn.addRequestProperty(header, value);
            }
        }

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setUseCaches(false);
        conn.setDoOutput(hasoutbody);

        if (postParameters != null && !postParameters.isEmpty()) {
            conn.setRequestMethod("POST");
            try (OutputStream requestBody = conn.getOutputStream()) {
                boolean first = true;
                for (Map.Entry<String, String> entry : postParameters.entrySet()) {
                    if (entry.getValue() == null)
                        continue;
                    if (first) {
                        first = false;
                    } else {
                        requestBody.write('&');
                    }
                    requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes());
                    requestBody.write('=');
                    requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes());
                }
            }
        } else {
            conn.setRequestMethod("GET");
        }

        StringBuilder responseBody = new StringBuilder();
        if (conn.getResponseCode() >= 400) {
            StringBuilder serverMessage = new StringBuilder();
            try (InputStream errorStream = conn.getErrorStream()) {
                if (errorStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = errorStream.read(buffer);
                        if (read <= 0)
                            break;
                        serverMessage.append(new String(buffer, 0, read));
                    }
                }
            }

            switch (conn.getResponseCode()) {
            case HttpServletResponse.SC_NOT_FOUND:
                responseBody.append("Kotlin compile server not found");
                break;
            case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
                responseBody.append("Kotlin compile server is temporary overloaded");
                break;
            default:
                responseBody = serverMessage;
                break;
            }
        } else {
            try (InputStream inputStream = conn.getInputStream()) {
                if (inputStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = inputStream.read(buffer);
                        if (read <= 0)
                            break;
                        responseBody.append(new String(buffer, 0, read));
                    }
                }
            }
        }
        writeResponse(request, response, responseBody.toString(), conn.getResponseCode());
    } catch (SocketTimeoutException e) {
        writeResponse(request, response, "Compile server connection timeout",
                HttpServletResponse.SC_GATEWAY_TIMEOUT);
    } catch (Exception e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "",
                "Can't forward request to Kotlin compile server");
        writeResponse(request, response, "Can't send your request to Kotlin compile server",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:cz.incad.kramerius.k5indexer.Commiter.java

/**
 * Reads data from the data reader and posts it to solr, writes the response
 * to output/*from   w  w  w . j a  va  2  s .  c  o  m*/
 */
private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception {
    HttpURLConnection urlc = null;

    try {
        urlc = (HttpURLConnection) url.openConnection();
        urlc.setConnectTimeout(config.getInt("http.timeout", 10000));
        try {
            urlc.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlc.setDoOutput(true);
        urlc.setDoInput(true);
        urlc.setUseCaches(false);
        urlc.setAllowUserInteraction(false);
        urlc.setRequestProperty("Content-type", contentType);

        OutputStream out = urlc.getOutputStream();

        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            pipe(data, writer);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        InputStream in = urlc.getInputStream();
        int status = urlc.getResponseCode();
        StringBuilder errorStream = new StringBuilder();
        try {
            if (status != HttpURLConnection.HTTP_OK) {
                errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=")
                        .append(status).append(" ");
                throw new Exception("URL=" + solrUrl + " HTTP response code=" + status);
            }
            Reader reader = new InputStreamReader(in);
            pipeString(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null) {
                in.close();
            }
        }

        InputStream es = urlc.getErrorStream();
        if (es != null) {
            try {
                Reader reader = new InputStreamReader(es);
                pipeString(reader, errorStream);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (es != null) {
                    es.close();
                }
            }
        }
        if (errorStream.length() > 0) {
            throw new Exception("postData error: " + errorStream.toString());
        }

    } catch (IOException e) {
        throw new Exception("Solr has throw an error. Check tomcat log. " + e);
    } finally {
        if (urlc != null) {
            urlc.disconnect();
        }
    }
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

private void loadBoards() {
    ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
        private List<NoticeListData> result = new ArrayList<NoticeListData>();

        @Override/*from  w w w .j  av  a  2  s .co  m*/
        protected Boolean doInBackground(String... params) {
            URL obj = null;
            try {
                obj = new URL("http://165.194.104.22:5000/board_notice");
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                //implement below code if token is send to server
                con = ConnectServer.getInstance().setHeader(con);

                con.setDoOutput(true);

                OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                wr.flush();

                BufferedReader rd = null;

                if (con.getResponseCode() == 200) {
                    rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                    String tmpString = rd.readLine();

                    JSONArray jsonArray = new JSONArray(tmpString);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);

                        Integer num = (Integer) object.get("num");
                        String title = (String) object.get("title");
                        String content = (String) object.get("content");
                        String time = (String) object.get("time");
                        Boolean isSignNeed = ((Integer) object.get("isSignNeed") != 0);
                        Boolean isImportant = ((Integer) object.get("isImportant") != 0);
                        Boolean isSignFinished = ((Integer) object.get("isSignFinished") != 0);

                        result.add(new NoticeListData(title, time, content, isSignNeed, isImportant,
                                isSignFinished));
                    }
                    Log.d("---- success ----", tmpString);
                } else {
                    rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                    Log.d("---- failed ----", String.valueOf(rd.readLine()));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Boolean value) {
            notice_adapter = new ListViewAdapter(getContext());
            notice_listView.setAdapter(notice_adapter);
            for (int i = 0; i < result.size(); i++) {
                notice_adapter.addNotice(result.get(i).mTitle, result.get(i).mContent, result.get(i).mDate,
                        result.get(i).isSignNeed, result.get(i).isImportant, result.get(i).isSignFinished);
            }
            Log.d(TAG, "notify called");
            notice_adapter.notifyDataSetChanged();
        }

    });
    ConnectServer.getInstance().execute();
}

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report./*from w  w  w . j a  va2  s  .  co  m*/
 *
 * @param context         the application context
 * @param withDevicesLogs true to include the device logs
 * @param withCrashLogs   true to include the crash logs
 */
private static void sendBugReport(final Context context, final boolean withDevicesLogs,
        final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) {
    new AsyncTask<Void, Integer, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report");

            if (bugReportFile.exists()) {
                bugReportFile.delete();
            }

            String serverError = null;
            FileWriter fileWriter = null;

            try {
                fileWriter = new FileWriter(bugReportFile);
                JsonWriter jsonWriter = new JsonWriter(fileWriter);
                jsonWriter.beginObject();

                // android bug report
                jsonWriter.name("user_agent").value("Android");

                // logs list
                jsonWriter.name("logs");
                jsonWriter.beginArray();

                // the logs are optional
                if (withDevicesLogs) {
                    List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>());
                    for (File f : files) {
                        if (!mIsCancelled) {
                            jsonWriter.beginObject();
                            jsonWriter.name("lines").value(convertStreamToString(f));
                            jsonWriter.endObject();
                            jsonWriter.flush();
                        }
                    }
                }

                if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) {
                    jsonWriter.beginObject();
                    jsonWriter.name("lines").value(getLogCatError());
                    jsonWriter.endObject();
                    jsonWriter.flush();
                }

                jsonWriter.endArray();

                jsonWriter.name("text").value(bugDescription);

                String version = "";

                if (null != Matrix.getInstance(context).getDefaultSession()) {
                    version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n";
                }

                version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " "
                        + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n";
                version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n";
                version += "SDK version:  " + Matrix.getInstance(context).getDefaultSession().getVersion(true)
                        + "\n";
                version += "Olm version:  "
                        + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true)
                        + "\n";

                jsonWriter.name("version").value(version);

                jsonWriter.endObject();
                jsonWriter.close();

            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage());
                serverError = e.getLocalizedMessage();
            } catch (OutOfMemoryError oom) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage());
                serverError = oom.getMessage();

                if (TextUtils.isEmpty(serverError)) {
                    serverError = "Out of memory";
                }
            }

            try {
                if (null != fileWriter) {
                    fileWriter.close();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage());
            }

            if (TextUtils.isEmpty(serverError) && !mIsCancelled) {

                // the screenshot is defined here
                // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg");
                InputStream inputStream = null;
                HttpURLConnection conn = null;
                try {
                    inputStream = new FileInputStream(bugReportFile);
                    final int dataLen = inputStream.available();

                    // should never happen
                    if (0 == dataLen) {
                        return "No data";
                    }

                    URL url = new URL(context.getResources().getString(R.string.bug_report_url));
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Content-Length", Integer.toString(dataLen));
                    // avoid caching data before really sending them.
                    conn.setFixedLengthStreamingMode(inputStream.available());

                    conn.connect();

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                    byte[] buffer = new byte[8192];

                    // read file and write it into form...
                    int bytesRead;
                    int totalWritten = 0;

                    while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
                        dos.write(buffer, 0, bytesRead);
                        totalWritten += bytesRead;
                        publishProgress(totalWritten * 100 / dataLen);
                    }

                    dos.flush();
                    dos.close();

                    int mResponseCode;

                    try {
                        // Read the SERVER RESPONSE
                        mResponseCode = conn.getResponseCode();
                    } catch (EOFException eofEx) {
                        mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
                    }

                    // if the upload failed, try to retrieve the reason
                    if (mResponseCode != HttpURLConnection.HTTP_OK) {
                        serverError = null;
                        InputStream is = conn.getErrorStream();

                        if (null != is) {
                            int ch;
                            StringBuilder b = new StringBuilder();
                            while ((ch = is.read()) != -1) {
                                b.append((char) ch);
                            }
                            serverError = b.toString();
                            is.close();

                            // check if the error message
                            try {
                                JSONObject responseJSON = new JSONObject(serverError);
                                serverError = responseJSON.getString("error");
                            } catch (JSONException e) {
                                Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage());
                            }

                            // should never happen
                            if (null == serverError) {
                                serverError = "Failed with error " + mResponseCode;
                            }

                            is.close();
                        }
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG,
                            "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage());
                    serverError = e.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Failed to upload";
                    }
                } catch (OutOfMemoryError oom) {
                    Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage());
                    serverError = oom.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Out ouf memory";
                    }

                } finally {
                    try {
                        if (null != conn) {
                            conn.disconnect();
                        }
                    } catch (Exception e2) {
                        Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage());
                    }
                }

                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage());
                    }
                }
            }
            return serverError;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            if (null != listener) {
                try {
                    listener.onProgress((null == progress) ? 0 : progress[0]);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage());
                }
            }
        }

        @Override
        protected void onPostExecute(String reason) {
            if (null != listener) {
                try {
                    if (mIsCancelled) {
                        listener.onUploadCancelled();
                    } else if (null == reason) {
                        listener.onUploadSucceed();
                    } else {
                        listener.onUploadFailed(reason);
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage());
                }
            }
        }
    }.execute();
}

From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java

/**
 * Post the formatted results to the gateway URL over HTTP 
 * //www  .  j  a va2s . c om
 * @param gatewayMessage String in the Stackdriver custom metrics JSON format containing the data points
 */
private void doSend(final String gatewayMessage) {
    HttpURLConnection urlConnection = null;

    try {
        if (proxy == null) {
            urlConnection = (HttpURLConnection) gatewayUrl.openConnection();
        } else {
            urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy);
        }
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(timeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey);

        // Stackdriver's own implementation does not specify char encoding
        // to use. Let's take the simplest approach and at lest ensure that
        // if we have problems they can be reproduced in consistant ways.
        // See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262
        // for details.
        urlConnection.getOutputStream().write(gatewayMessage.getBytes(ISO_8859_1));

        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200 && responseCode != 201) {
            logger.warn("Failed to send results to Stackdriver server: responseCode=" + responseCode
                    + " message=" + urlConnection.getResponseMessage());
        }
    } catch (Exception e) {
        logger.warn("Failure to send result to Stackdriver server", e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                in.close();
                InputStream err = urlConnection.getErrorStream();
                if (err != null) {
                    err.close();
                }
                urlConnection.disconnect();
            } catch (IOException e) {
                logger.warn("Error flushing http connection for one result, continuing");
                logger.debug("Stack trace for the http connection, usually a network timeout", e);
            }
        }

    }
}

From source file:github.nisrulz.optimushttp.HttpReq.java

@Override
protected String doInBackground(HttpReqPkg... params) {

    URL url;/*from   ww w  .j a  va  2s  .  com*/
    BufferedReader reader = null;

    String username = params[0].getUsername();
    String password = params[0].getPassword();
    String authStringEnc = null;

    if (username != null && password != null) {
        String authString = username + ":" + password;

        byte[] authEncBytes;
        authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        authStringEnc = new String(authEncBytes);
    }

    String uri = params[0].getUri();

    if (params[0].getMethod().equals("GET")) {
        uri += "?" + params[0].getEncodedParams();
    }

    try {
        StringBuilder sb;
        // create the HttpURLConnection
        url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (authStringEnc != null) {
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")
                || params[0].getMethod().equals("DELETE")) {
            // enable writing output to this url
            connection.setDoOutput(true);
        }

        if (params[0].getMethod().equals("POST")) {
            connection.setRequestMethod("POST");
        } else if (params[0].getMethod().equals("GET")) {
            connection.setRequestMethod("GET");
        } else if (params[0].getMethod().equals("PUT")) {
            connection.setRequestMethod("PUT");
        } else if (params[0].getMethod().equals("DELETE")) {
            connection.setRequestMethod("DELETE");
        }

        // give it x seconds to respond
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);

        for (int i = 0; i < headerMap.size(); i++) {
            connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
        }

        connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length);

        connection.connect();
        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(params[0].getEncodedParams());
            writer.flush();
            writer.close();
        }

        // read the output from the server
        InputStream in;
        resCode = connection.getResponseCode();
        resMsg = connection.getResponseMessage();
        if (resCode != HttpURLConnection.HTTP_OK) {
            in = connection.getErrorStream();
        } else {
            in = connection.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        sb.append(resCode).append(" : ").append(resMsg);
        return sb.toString();
    } catch (Exception e) {
        listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
        e.printStackTrace();
    } finally {
        // close the reader; this can throw an exception too, so
        // wrap it in another try/catch block.
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return null;
}

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  ww  .j  ava 2s .c  om*/
        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:org.andstatus.app.net.http.HttpConnectionOAuthJavaNet.java

protected void getRequest(HttpReadResult result) throws ConnectionException {
    String method = "getRequest; ";
    StringBuilder logBuilder = new StringBuilder(method);
    try {//from   ww w .j  a va 2s  . co  m
        OAuthConsumer consumer = getConsumer();
        logBuilder.append("URL='" + result.getUrl() + "';");
        HttpURLConnection conn;
        boolean redirected = false;
        boolean stop = false;
        do {
            conn = (HttpURLConnection) result.getUrlObj().openConnection();
            conn.setInstanceFollowRedirects(false);
            if (result.authenticate) {
                setAuthorization(conn, consumer, redirected);
            }
            conn.connect();
            result.setStatusCode(conn.getResponseCode());
            switch (result.getStatusCode()) {
            case OK:
                if (result.fileResult != null) {
                    HttpConnectionUtils.readStreamToFile(conn.getInputStream(), result.fileResult);
                } else {
                    result.strResponse = HttpConnectionUtils.readStreamToString(conn.getInputStream());
                }
                stop = true;
                break;
            case MOVED:
                redirected = true;
                result.setUrl(conn.getHeaderField("Location").replace("%3F", "?"));
                String logMsg3 = (result.redirected ? "Following redirect to " : "Not redirected to ") + "'"
                        + result.getUrl() + "'";
                logBuilder.append(logMsg3 + "; ");
                MyLog.v(this, method + logMsg3);
                if (MyLog.isLoggable(MyLog.APPTAG, MyLog.VERBOSE)) {
                    StringBuilder message = new StringBuilder(method + "Headers: ");
                    for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
                        for (String value : entry.getValue()) {
                            message.append(entry.getKey() + ": " + value + ";\n");
                        }
                    }
                    MyLog.v(this, message.toString());
                }
                conn.disconnect();
                break;
            default:
                result.strResponse = HttpConnectionUtils.readStreamToString(conn.getErrorStream());
                stop = result.fileResult == null || !result.authenticate;
                if (!stop) {
                    result.authenticate = false;
                    String logMsg4 = "Retrying without authentication connection to '" + result.getUrl() + "'";
                    logBuilder.append(logMsg4 + "; ");
                    MyLog.v(this, method + logMsg4);
                }
                break;
            }
        } while (!stop);
    } catch (ConnectionException e) {
        throw e;
    } catch (IOException e) {
        throw new ConnectionException(logBuilder.toString(), e);
    }
}