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:export.Strava.java

@Override
public Uploader.Status upload(SQLiteDatabase db, final long mID) {
    Status s;//from   w w w. ja va  2 s .co  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("POST");

        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.filename = "RunnerUp.tcx";
        part2.contentType = "application/octet-stream";
        Part<?> parts[] = { part0, part1, part2 };
        postMulti(conn, parts);

        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        System.err.println("code: " + responseCode + ", amsg: " + amsg);

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

        if (responseCode == 201 && obj.getLong("id") > 0) {
            conn.disconnect();
            return Status.OK;
        }
        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;
}

From source file:com.event.app.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 www.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) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:hudson.remoting.Launcher.java

/**
 * Parses the connection arguments from JNLP file given in the URL.
 *//*  w  ww .  j  a  v  a 2 s . c o  m*/
public List<String> parseJnlpArguments()
        throws ParserConfigurationException, SAXException, IOException, InterruptedException {
    while (true) {
        try {
            URLConnection con = slaveJnlpURL.openConnection();
            if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) {
                HttpURLConnection http = (HttpURLConnection) con;
                String userPassword = slaveJnlpCredentials;
                String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
                http.setRequestProperty("Authorization", "Basic " + encoding);
            }
            con.connect();

            if (con instanceof HttpURLConnection) {
                HttpURLConnection http = (HttpURLConnection) con;
                if (http.getResponseCode() >= 400)
                    // got the error code. report that (such as 401)
                    throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " "
                            + http.getResponseMessage());
            }

            Document dom;

            // check if this URL points to a .jnlp file
            String contentType = con.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) {
                // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
                try {
                    dom = loadDom(slaveJnlpURL, con);
                } catch (SAXException e) {
                    throw new IOException(
                            slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                } catch (IOException e) {
                    throw new IOException(
                            slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                }
            } else {
                dom = loadDom(slaveJnlpURL, con);
            }

            // exec into the JNLP launcher, to fetch the connection parameter through JNLP.
            NodeList argElements = dom.getElementsByTagName("argument");
            List<String> jnlpArgs = new ArrayList<String>();
            for (int i = 0; i < argElements.getLength(); i++)
                jnlpArgs.add(argElements.item(i).getTextContent());
            if (slaveJnlpCredentials != null) {
                jnlpArgs.add("-credentials");
                jnlpArgs.add(slaveJnlpCredentials);
            }
            // force a headless mode
            jnlpArgs.add("-headless");
            return jnlpArgs;
        } catch (SSLHandshakeException e) {
            if (e.getMessage().contains("PKIX path building failed")) {
                // invalid SSL certificate. One reason this happens is when the certificate is self-signed
                IOException x = new IOException(
                        "Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
                x.initCause(e);
                throw x;
            } else
                throw e;
        } catch (IOException e) {
            System.err.println("Failing to obtain " + slaveJnlpURL);
            e.printStackTrace(System.err);
            System.err.println("Waiting 10 seconds before retry");
            Thread.sleep(10 * 1000);
            // retry
        }
    }
}

From source file:com.miya38.connection.volley.CustomHurlStack.java

@Override
public HttpResponse performRequest(final Request<?> request, final Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    final HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from ww w .j av a2 s . c  om
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        final String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    final URL parsedUrl = new URL(url);
    final HttpURLConnection connection = openConnection(parsedUrl, request);
    for (final String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    final 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.");
    }
    final StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    final BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (final Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            // bug fix y-miyazaki start
            for (final String value : header.getValue()) {
                final Header h = new BasicHeader(header.getKey(), value);
                response.addHeader(h);
            }
            // bug fix y-miyazaki end
        }
    }
    return response;
}

From source file:cn.bidaround.ytcore.util.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());/*ww  w.  j av  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) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.playbasis.android.playbasissdk.http.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());//ww  w . ja v a 2 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);
    HttpURLConnection connection = (HttpURLConnection) parsedUrl.openConnection();//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:it.infn.ct.jsaga.adaptor.tosca.job.ToscaJobControlAdaptor.java

private String submitTosca() throws IOException, ParseException, BadResource, NoSuccessException {
    StringBuilder orchestrator_result = new StringBuilder("");
    StringBuilder postData = new StringBuilder();
    postData.append("{ \"template\": \"");
    String tosca_template_content = "";
    try {//  w  ww . j av a2s  .  c o m
        tosca_template_content = new String(Files.readAllBytes(Paths.get(tosca_template))).replace("\n", "\\n");
        postData.append(tosca_template_content);
    } catch (IOException ex) {
        log.error("Template '" + tosca_template + "'is not readable");
        throw new BadResource("Template '" + tosca_template + "'is not readable; template:" + LS + "'"
                + tosca_template_content + "'");
    }
    postData.append("\"  }");

    log.debug("JSON Data sent to the orchestrator: \n" + postData);
    HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postData.toString());
        wr.flush();
        wr.close();
        log.debug("Orchestrator status code: " + conn.getResponseCode());
        log.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == 201) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            orchestrator_result = new StringBuilder();
            String ln;
            while ((ln = br.readLine()) != null) {
                orchestrator_result.append(ln);
            }

            log.debug("Orchestrator result: " + orchestrator_result);
            String orchestratorDoc = orchestrator_result.toString();
            tosca_UUID = getDocumentValue(orchestratorDoc, "uuid");
            log.debug("Created resource has UUID: '" + tosca_UUID + "'");
            return orchestratorDoc;

        }
    } catch (IOException ex) {
        log.error("Connection error with the service at " + endpoint.toString());
        log.error(ex);
        throw new NoSuccessException("Connection error with the service at " + endpoint.toString());
    } catch (ParseException ex) {
        log.error("Orchestrator response not parsable");
        throw new NoSuccessException(
                "Orchestrator response not parsable:" + LS + "'" + orchestrator_result.toString() + "'");
    }
    return tosca_UUID;
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

public HttpResponse request() {
    if (mDebug) {
        FLog.i("REQUEST URL:" + mUrlString);
        FLog.i("REQUEST PARAMS:" + mRequestParams.getArrayMap().toString());
        FLog.i("REQUEST STRING:" + mRequestParams.getString());
    }//from w w w.  j  a v  a2  s.com

    if (mStackTrace) {
        getInvokeStackTraceElement();
    }

    HttpResponse response = new HttpResponse();
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(mUrlString).openConnection();
        configConnection(connection);
        response.code = connection.getResponseCode();
        if (mDebug)
            FLog.i("===responseCode:" + response.code);
        if (response.code == HttpURLConnection.HTTP_OK) {
            String responseText = IoUtils.readStream(connection.getInputStream());
            String cookie = connection.getHeaderField("Set-Cookie");
            if (mDebug)
                FLog.i("===responseText:" + responseText);
            if (mDebug)
                FLog.i("===cookie:" + cookie);
            response.cookies = HttpCookie.parse(cookie);
            response.text = responseText;
        } else {
            response.text = connection.getResponseMessage();
        }
    } catch (UnknownHostException e) {
        if (mDebug)
            FLog.e(e);
        response.code = HttpResponse.STATUS_CODE_NET;
        response.text = "";
        return response;
    } catch (IOException e) {
        if (mDebug)
            FLog.e(e);
        response.code = HttpResponse.STATUS_CODE_UNKNOWN;
        response.text = "UNKNOWN";
        return response;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return response;
}

From source file:com.mars.framework.volley.net.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  .  j av 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);
    connection.setChunkedStreamingMode(0);
    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.openrdf.http.server.ProtocolTest.java

private TupleQueryResult evaluateTupleQuery(String location, String query, QueryLanguage queryLn)
        throws Exception {
    location += "?query=" + URLEncoder.encode(query, "UTF-8") + "&queryLn=" + queryLn.getName();

    URL url = new URL(location);

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

    // Request SPARQL-XML formatted results:
    conn.setRequestProperty("Accept", TupleQueryResultFormat.SPARQL.getDefaultMIMEType());

    conn.connect();/*from   w ww.  j  a v  a 2  s  .c om*/

    try {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Process query results
            return QueryResultIO.parseTuple(conn.getInputStream(), TupleQueryResultFormat.SPARQL);
        } else {
            String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
                    + responseCode + ")";
            fail(response);
            throw new RuntimeException(response);
        }
    } finally {
        conn.disconnect();
    }
}