Example usage for java.net HttpURLConnection getResponseMessage

List of usage examples for java.net HttpURLConnection getResponseMessage

Introduction

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

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:org.peterbaldwin.vlcremote.sweep.Worker.java

@Override
public void run() {
    // Note: InetAddress#isReachable(int) always returns false for Windows
    // hosts because applications do not have permission to perform ICMP
    // echo requests.
    for (;;) {//from w  w  w  .j  av  a  2 s  . c o  m
        byte[] ipAddress = mManager.pollIpAddress();
        if (ipAddress == null) {
            break;
        }
        try {
            InetAddress address = InetAddress.getByAddress(ipAddress);
            String hostAddress = address.getHostAddress();
            URL url = createUrl("http", hostAddress, mPort, mPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            try {
                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK)
                        ? connection.getInputStream()
                        : connection.getErrorStream();
                if (inputStream != null) {
                    try {
                        int length = connection.getContentLength();
                        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
                        entity.setContentType(connection.getContentType());

                        // Copy the entire response body into memory
                        // before the HTTP connection is closed:
                        String body = EntityUtils.toString(entity);

                        ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1);
                        String hostname = address.getHostName();
                        StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage);
                        HttpResponse response = new BasicHttpResponse(statusLine);
                        response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort);
                        response.setEntity(new StringEntity(body));
                        mCallback.onReachable(ipAddress, response);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    Log.w(TAG, "InputStream is null");
                }
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, e);
        }
    }
}

From source file:org.apache.hadoop.yarn.client.TestRMFailover.java

private void verifyResponse(HttpURLConnection response) throws IOException {
    assertEquals("Not Found", response.getResponseMessage());
    assertEquals(404, response.getResponseCode());
}

From source file:com.baidu.jprotobuf.rpc.client.SimpleHttpRequestExecutor.java

/**
 * Validate the given response as contained in the HttpURLConnection object,
 * throwing an exception if it does not correspond to a successful HTTP response.
 * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid
 * parsing the response body and trying to deserialize from a corrupted stream.
 * @param con the HttpURLConnection to validate
 * @throws IOException if validation failed
 * @see java.net.HttpURLConnection#getResponseCode()
 *///from   w  w  w  . j av a 2  s  . c  o m
protected void validateResponse(HttpURLConnection con) throws IOException {

    if (con.getResponseCode() >= 300) {
        throw new IOException("Did not receive successful HTTP response: status code = " + con.getResponseCode()
                + ", status message = [" + con.getResponseMessage() + "]");
    }
}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

public static String getToken(final String username, final String password) {
    try {/* www  .  ja v a 2s. com*/
        final HttpURLConnection urlConnection = getConnection("/authorization/token");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        JSONObject request = new JSONObject();
        request.put("username", username);
        request.put("password", password);
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        Log.d("SipgateApi", request.getString("username"));
        wr.write(request.toString());
        wr.flush();
        StringBuilder sb = new StringBuilder();
        int HttpResult = urlConnection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            Log.d("SipgateApi", "" + sb.toString());
            final JSONObject response = new JSONObject(sb.toString());
            return response.getString("token");
        } else {
            System.out.println(urlConnection.getResponseMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:eu.faircode.netguard.DownloadTask.java

@Override
protected Object doInBackground(Object... args) {
    Log.i(TAG, "Downloading " + url + " into " + file);

    InputStream in = null;/*from  w w w . ja v a  2s  . c  o m*/
    OutputStream out = null;
    URLConnection connection = null;
    try {
        connection = url.openConnection();
        connection.connect();

        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
                throw new IOException(
                        httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
        }

        int contentLength = connection.getContentLength();
        Log.i(TAG, "Content length=" + contentLength);
        in = connection.getInputStream();
        out = new FileOutputStream(file);

        long size = 0;
        byte buffer[] = new byte[4096];
        int bytes;
        while (!isCancelled() && (bytes = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes);

            size += bytes;
            if (contentLength > 0)
                publishProgress((int) (size * 100 / contentLength));
        }

        Log.i(TAG, "Downloaded size=" + size);
        return null;
    } catch (Throwable ex) {
        return ex;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
        try {
            if (in != null)
                in.close();
        } catch (IOException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        if (connection instanceof HttpURLConnection)
            ((HttpURLConnection) connection).disconnect();
    }
}

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

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {// ww w . j a va2 s .co  m
    /*  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:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doGet(String endpoint, Map<String, String> headers) throws IOException {
    HttpResponse httpResponse;//from  www.j av  a2  s.  c o m
    if (endpoint.startsWith("http://")) {
        URL url = new URL(endpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setReadTimeout(30000);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                conn.setRequestProperty(key, headers.get(key));
            }
        }

        conn.connect();

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
            httpResponse.setResponseMessage(conn.getResponseMessage());

        } catch (IOException ignored) {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
            httpResponse.setResponseMessage(conn.getResponseMessage());
        } finally {
            if (rd != null) {
                rd.close();
            }
        }

        return httpResponse;
    }
    return null;
}

From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java

/**
 * Performs a network request call to the specified URL and parameters.
 * /*from w  w  w. j  a  v a 2s  . c  o  m*/
 * @param url                     The base URL.
 * @param params                  The URL parameters.
 * @return                         Response from the server.
 */
public String connectToURL(String url, String params) {
    String httpResponse = null;

    BufferedReader rd = null;
    StringBuilder sb = null;
    String line = null;

    try {
        String requestURL = url + params;

        // Replaces all spaces.
        requestURL = requestURL.replaceAll(" ", "%20");

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "baseURL: " + url);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL);

        // USE java.net HTTP connection instead.

        URL httpURL = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        httpResponse = connection.getResponseMessage();

        connection.connect();

        // Read the result from the server.
        rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        sb = new StringBuilder();

        while ((line = rd.readLine()) != null) {
            sb.append(line + '\n');
        }

        httpResponse = sb.toString();

        // OLD CODE USING APACHE API

        // HttpGet http = new HttpGet(requestURL);
        //
        // // Create a HttpParams object so we can set our timeout times.
        // HttpParams httpParameters = new BasicHttpParams();
        //
        // // Time to wait to establish initial connection.
        // HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
        //
        // // Time to wait for incoming data.
        // HttpConnectionParams.setSoTimeout(httpParameters, 30000);
        //
        // // Create a http client with out timeout settings.
        // HttpClient client = new DefaultHttpClient(httpParameters);
        //
        // HttpResponse response = client.execute(http);
        // HttpEntity entity = response.getEntity();
        //
        // httpResponse = EntityUtils.toString(entity);

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
        // TapjoyLog.i(TAPJOY_URL_CONNECTION, "response status: " + response.getStatusLine().getStatusCode());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response size: " + httpResponse.length());
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "response: ");
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "" + httpResponse);
        TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------");
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString());
    }

    return httpResponse;
}

From source file:org.akvo.flow.api.FlowApi.java

private String httpGet(String url) throws IOException, ApiException {
    HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());
    final long t0 = System.currentTimeMillis();
    try {// w  w w .java2s.  c  o  m
        int status = getStatusCode(conn);
        if (status != HttpStatus.SC_OK) {
            throw new ApiException(conn.getResponseMessage(), status);
        }
        InputStream in = new BufferedInputStream(conn.getInputStream());
        String response = readStream(in);
        Log.d(TAG, "Request time: " + (System.currentTimeMillis() - t0) + ". URL: " + url);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:eu.faircode.netguard.ServiceExternal.java

@Override
protected void onHandleIntent(Intent intent) {
    try {// www.  j a  v  a2 s .  c  om
        startForeground(ServiceSinkhole.NOTIFY_EXTERNAL, getForegroundNotification(this));

        Log.i(TAG, "Received " + intent);
        Util.logExtras(intent);

        if (ACTION_DOWNLOAD_HOSTS_FILE.equals(intent.getAction())) {
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

            String hosts_url = prefs.getString("hosts_url", null);
            File tmp = new File(getFilesDir(), "hosts.tmp");
            File hosts = new File(getFilesDir(), "hosts.txt");

            InputStream in = null;
            OutputStream out = null;
            URLConnection connection = null;
            try {
                URL url = new URL(hosts_url);
                connection = url.openConnection();
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
                        throw new IOException(
                                httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
                }

                int contentLength = connection.getContentLength();
                Log.i(TAG, "Content length=" + contentLength);
                in = connection.getInputStream();
                out = new FileOutputStream(tmp);

                long size = 0;
                byte buffer[] = new byte[4096];
                int bytes;
                while ((bytes = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes);
                    size += bytes;
                }

                Log.i(TAG, "Downloaded size=" + size);

                if (hosts.exists())
                    hosts.delete();
                tmp.renameTo(hosts);

                String last = SimpleDateFormat.getDateTimeInstance().format(new Date().getTime());
                prefs.edit().putString("hosts_last_download", last).apply();

                ServiceSinkhole.reload("hosts file download", this, false);

            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));

                if (tmp.exists())
                    tmp.delete();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
                try {
                    if (in != null)
                        in.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }

                if (connection instanceof HttpURLConnection)
                    ((HttpURLConnection) connection).disconnect();
            }
        }
    } finally {
        stopForeground(true);
    }
}