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:com.farru.android.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();

    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from w  w w.  j a  va 2s.com
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.chen.cy.talkimage.network.xvolley.XHurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//w w w . ja  v  a 2  s . c o m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            //
            // ?????
            for (int i = 0; i < header.getValue().size(); i++) {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(i));
                response.addHeader(h);
            }
        }
    }
    return response;
}

From source file:eu.codeplumbers.cosi.services.CosiFileDownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiFileDownloadService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // cozy register device url
    fileUrl = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();//from w ww.ja va  2  s.  co m

    if (isNetworkAvailable()) {
        try {

            ArrayList<String> fileStrings = intent.getStringArrayListExtra("fileToDownload");

            for (int i = 0; i < fileStrings.size(); i++) {
                File file = File.load(File.class, Long.valueOf(fileStrings.get(i)));
                String binaryRemoteId = file.getRemoteId();

                if (!binaryRemoteId.isEmpty()) {
                    mBuilder.setProgress(100, 0, false);
                    mBuilder.setContentText("Downloading file: " + file.getName());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    URL urlO = null;
                    try {
                        urlO = new URL(fileUrl + binaryRemoteId + "/binaries/file");
                        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
                        conn.setConnectTimeout(5000);
                        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                        conn.setRequestProperty("Authorization", authHeader);
                        conn.setDoInput(true);
                        conn.setRequestMethod("GET");

                        conn.connect();
                        int lenghtOfFile = conn.getContentLength();

                        // read the response
                        int status = conn.getResponseCode();

                        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                            EventBus.getDefault()
                                    .post(new FileSyncEvent(SERVICE_ERROR, conn.getResponseMessage()));
                            stopSelf();
                        } else {
                            int count = 0;
                            InputStream in = new BufferedInputStream(conn.getInputStream(), 8192);

                            java.io.File newFile = file.getLocalPath();

                            if (!newFile.exists()) {
                                newFile.createNewFile();
                            }

                            // Output stream to write file
                            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
                                    + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator
                                    + "files" + file.getPath() + "/" + file.getName());

                            byte data[] = new byte[1024];
                            long total = 0;
                            while ((count = in.read(data)) != -1) {
                                total += count;

                                mBuilder.setProgress(lenghtOfFile, (int) total, false);
                                mBuilder.setContentText("Downloading file: " + file.getName());
                                mNotifyManager.notify(notification_id, mBuilder.build());

                                // writing data to file
                                output.write(data, 0, count);
                            }

                            // flushing output
                            output.flush();

                            // closing streams
                            output.close();
                            in.close();

                            file.setDownloaded(true);
                            file.save();
                        }
                    } catch (MalformedURLException e) {
                        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    } catch (ProtocolException e) {
                        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    } catch (IOException e) {
                        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new FileSyncEvent(REFRESH, "Sync OK"));
        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:com.oplay.nohelper.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError, NetworkError {
    if (request.getHasHttpResponse()) {
        throw new NetworkError("Slow Network leads to more HttpResponse");
    }//ww w.  j  a v  a2 s  .c om
    String url = request.getUrl();
    request.addMarker(url);
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    request.addMarker("network-http-complete");
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

@Override
@SuppressWarnings("deprecation")
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(request.getHeaders());/*from   w w  w.ja  v a2 s . co  m*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    OkUrlFactory okFactory = new OkUrlFactory(mClient);
    HttpURLConnection connection = openOkHttpURLConnection(okFactory, parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java

/**
 * Checks that a proper error (HTTP 406) is returned when accept header is set incorrectly on graph query.
 *//*  ww  w.  j a  v a2 s  .  c o m*/
@Test
public void testContentTypeForGraphQuery2_GET() throws Exception {
    String query = "DESCRIBE <foo:bar>";
    String location = TestServer.REPOSITORY_URL;
    location += "?query=" + URLEncoder.encode(query, "UTF-8");

    URL url = new URL(location);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // incorrect mime-type for graph query results
    conn.setRequestProperty("Accept", TupleQueryResultFormat.SPARQL.getDefaultMIMEType());

    conn.connect();

    try {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NOT_ACCEPTABLE) {
            // do nothing, expected
        } else {
            String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
                    + responseCode + ")";
            fail(response);
        }
    } finally {
        conn.disconnect();
    }
}

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private JSONObject readJSONObjectFromUrlPOST(String urlString, Map<String, String> headers, String payload)
        throws IOException, JSONException {
    URL url = new URL(urlString);
    HttpURLConnection connection = getConnection(urlString);

    connection.setRequestMethod(POST);/*from  w w  w  .j  a v  a2  s  . c  o m*/
    connection.setDoOutput(true);

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    OutputStream os = connection.getOutputStream();
    os.write(payload.getBytes());
    os.flush();

    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK
            && connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode() + " : "
                + connection.getResponseMessage());
    }

    InputStream content = connection.getInputStream();
    return readAllIntoJSONObject(content);
}

From source file:com.example.httpjson.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;//from w  w w.jav  a2 s. c om
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

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

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                if (a == 401) {
                    response = new Response(a, conn.getHeaderFields(), new byte[] {});
                }
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

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;// w ww .  j av  a 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:com.android.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//  w w w .j a v  a 2 s  .c  om
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}