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.example.pabrto.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;//from w w w . ja  v a 2  s  . c o m
    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();
                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.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.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  a2  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);
    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.apache.hadoop.fs.http.client.HttpFSFileSystem.java

/**
 * Validates the status of an <code>HttpURLConnection</code> against an
 * expected HTTP status code. If the current status code is not the expected
 * one it throws an exception with a detail message using Server side error
 * messages if available./*from  ww w  .  j a  v  a2s.com*/
 * 
 * @param conn
 *            the <code>HttpURLConnection</code>.
 * @param expected
 *            the expected HTTP status code.
 * 
 * @throws IOException
 *             thrown if the current status code does not match the expected
 *             one.
 */
private static void validateResponse(HttpURLConnection conn, int expected) throws IOException {
    int status = conn.getResponseCode();
    if (status != expected) {
        try {
            JSONObject json = (JSONObject) jsonParse(conn);
            json = (JSONObject) json.get(ERROR_JSON);
            String message = (String) json.get(ERROR_MESSAGE_JSON);
            String exception = (String) json.get(ERROR_EXCEPTION_JSON);
            String className = (String) json.get(ERROR_CLASSNAME_JSON);

            try {
                ClassLoader cl = HttpFSFileSystem.class.getClassLoader();
                Class klass = cl.loadClass(className);
                Constructor constr = klass.getConstructor(String.class);
                throw (IOException) constr.newInstance(message);
            } catch (IOException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new IOException(MessageFormat.format("{0} - {1}", exception, message));
            }
        } catch (IOException ex) {
            if (ex.getCause() instanceof IOException) {
                throw (IOException) ex.getCause();
            }
            throw new IOException(
                    MessageFormat.format("HTTP status [{0}], {1}", status, conn.getResponseMessage()));
        }
    }
}

From source file:com.yaozu.object.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  ww .jav  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);
    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;
}

From source file:com.selene.volley.stack.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>();
    //      if (!TextUtils.isEmpty(mUserAgent)) {
    //         map.put(HTTP.USER_AGENT, mUserAgent);
    //      }/*from   w ww. jav a 2  s .  co m*/
    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);
    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;
}

From source file:com.vimc.ahttp.HurlWorker.java

@Override
public HttpResponse doHttpRquest(Request<?> request) throws IOException {
    String url = request.getUrl();

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }/*  w w w .  j a v a  2  s .c  om*/
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    addHeadersIfExists(request, connection);
    setConnectionParametersByRequest(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:be.wimsymons.intellij.polopolyimport.PPImporter.java

private void postData(final String name, final Reader reader, final String contentType,
        final String extraParams) throws IOException {
    Writer writer = null;//from w  ww  .jav a 2  s . c om
    LOGGER.info("Doing HTTP POST for " + name);
    try {
        URL httpURL = buildURL(target, extraParams);

        HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection();
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestMethod("PUT");
        httpConnection.setRequestProperty("Content-Type", contentType);
        httpConnection.setConnectTimeout(2000);
        httpConnection.setReadTimeout(60000);
        httpConnection.connect();

        if (contentType.contains("UTF-8")) {
            copyAndFlush(reader, httpConnection.getOutputStream());
        } else {
            writer = new OutputStreamWriter(httpConnection.getOutputStream());
            CharStreams.copy(reader, writer);
            writer.flush();
        }

        int responseCode = httpConnection.getResponseCode();
        String responseMessage = httpConnection.getResponseMessage();
        if (responseCode < 200 || responseCode >= 300) {
            failureCount++;
            PPImportPlugin.doNotify("Import of " + name + " failed: " + responseCode + " - " + responseMessage
                    + "\nCheck the server log for more details.", NotificationType.ERROR);
        } else {
            successCount++;
        }
    } catch (IOException e) {
        failureCount++;
        PPImportPlugin.doNotify("Import of " + name + " failed: " + e.getMessage(), NotificationType.ERROR);
    } finally {
        Closeables.close(reader, true);
        Closeables.close(writer, true);
    }
}

From source file:com.kubeiwu.commontool.khttp.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());//
    map.putAll(additionalHeaders);/*from   w  w w. j  av a2s .  c om*/
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);// ?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()) {// header
        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);
            //cookie?
            String key = header.getKey();
            List<String> values = header.getValue();
            if (key.equalsIgnoreCase("set-cookie")) {
                StringBuilder cookieString = new StringBuilder();
                for (String value : values) {
                    cookieString.append(value).append("\n");// \ncookie??
                }
                cookieString.deleteCharAt(cookieString.length() - 1);
                Header h = new BasicHeader(header.getKey(), cookieString.toString());
                response.addHeader(h);
            } else {
                Header h = new BasicHeader(header.getKey(), values.get(0));
                response.addHeader(h);
            }
        }
    }
    System.out.println("performRequest---999999-getStatusLine=" + response.getStatusLine());
    return response;
}

From source file:org.runnerup.export.StravaSynchronizer.java

@Override
public Status upload(SQLiteDatabase db, final long mID) {
    Status s;/*from w  w w .  ja va  2s .  c o  m*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    String URL = REST_URL;
    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(URL).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());

        Part<StringWritable> part0 = new Part<StringWritable>("access_token", new StringWritable(access_token));
        Part<StringWritable> part1 = new Part<StringWritable>("data_type", new StringWritable("tcx"));
        Part<StringWritable> part2 = new Part<StringWritable>("file", new StringWritable(writer.toString()));
        part2.setFilename("RunnerUp.tcx");
        part2.setContentType("application/octet-stream");
        Part<?> parts[] = { part0, part1, part2 };
        SyncHelper.postMulti(conn, parts);

        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        Log.e(getName(), "code: " + responseCode + ", amsg: " + amsg);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        JSONObject obj = SyncHelper.parse(in);

        if (responseCode == HttpStatus.SC_CREATED && obj.getLong("id") > 0) {
            conn.disconnect();
            s = Status.OK;
            s.activityId = mID;
            return s;
        }
        ex = new Exception(amsg);
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    s.activityId = mID;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:export.GarminUploader.java

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;/*w  ww. j a  v a 2s .c om*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        addCookies(conn);
        Part<StringWritable> part2 = new Part<StringWritable>("data", new StringWritable(writer.toString()));
        part2.filename = "RunnerUp.tcx";
        part2.contentType = "application/octet-stream";
        Part<?> parts[] = { part2 };
        postMulti(conn, parts);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        if (responseCode == 200) {
            JSONObject reply = parse(new BufferedReader(new InputStreamReader(conn.getInputStream())));
            conn.disconnect();
            JSONObject result = reply.getJSONObject("detailedImportResult");
            if (result.getJSONArray("successes").length() == 1)
                return Status.OK;
            else
                ex = new Exception("Unexpected reply: " + reply.toString());
        } else {
            ex = new Exception(amsg);
        }
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    s = Uploader.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}