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.xjb.volley.toobox.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 .  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()) {
        try {
            connection.addRequestProperty(headerName, map.get(headerName));
        } catch (Exception e) {

        }
    }
    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) {
            synchronized (HurlStack.class) {
                if (header.getKey().equals("Set-Cookie")) {
                    String cookie = "";
                    List<String> list = header.getValue();
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).contains("IHOME_FRONT_SID")) {
                                String[] ss = list.get(i).split(";");
                                cookie = ss[0];
                            }
                        }
                    }
                    Header h = new BasicHeader(header.getKey(), cookie);
                    response.addHeader(h);
                } else {

                    Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                    response.addHeader(h);

                }

            }

        }
    }
    return response;
}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java

@Override
protected String doInBackground(File... files) {
    for (int i = 0; i < files.length; i++) {
        File file = files[i];//from w w w.j  a v  a 2  s  . c o m
        String binaryRemoteId = file.getRemoteId();

        if (!binaryRemoteId.isEmpty()) {
            publishProgress("Deleting file: " + file.getName(), "0", "100");
            URL urlO = null;
            try {
                urlO = new URL(url + 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("DELETE");
                InputStream in = null;

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

                if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                    in = conn.getErrorStream();
                } else {
                    in = conn.getInputStream();
                }

                StringWriter writer = new StringWriter();
                IOUtils.copy(in, writer, "UTF-8");
                String result = writer.toString();

                if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                    errorMessage = conn.getResponseMessage();
                } else {
                    errorMessage = deleteFileRequest(file);

                    if (errorMessage == "") {
                        java.io.File newFile = file.getLocalPath();

                        if (newFile.exists()) {
                            newFile.delete();
                        }
                        file.delete();
                    } else {
                        return errorMessage;
                    }

                }
            } catch (MalformedURLException e) {
                errorMessage = e.getLocalizedMessage();
            } catch (ProtocolException e) {
                errorMessage = e.getLocalizedMessage();
            } catch (IOException e) {
                errorMessage = e.getLocalizedMessage();
            }
        }
    }

    return errorMessage;
}

From source file:common.net.volley.toolbox.HurlStack.java

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

    stethoManager = new StethoURLConnectionManager(url);

    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*from  ww w .java2 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);
    requestDecompression(connection);

    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());

    stethoManager.postConnect();

    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

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 w  w .  j av a  2  s .  com

    try {
        int responseCode = conn.getResponseCode();
        // HTTP 200
        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();
    }
}

From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*  w  w  w .ja  va2s.  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);

    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode;
    try {
        responseCode = connection.getResponseCode();
    } catch (IOException e) {
        // 4.1.x/4.2.x/4.3.x ? (WWW-Authenticate: Basic realm="XXX")
        // ??401
        // java.io.IOException: No authentication challenges found
        // ?getResponseCode??
        responseCode = connection.getResponseCode();
    }
    if (responseCode == -1) {
        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) {
            String value = "";
            for (String v : header.getValue()) {
                value += (v + "; ");
            }
            Header h = new BasicHeader(header.getKey(), value);
            response.addHeader(h);
        }
    }
    return response;
}

From source file:de.mpg.mpdl.inge.pubman.web.util.FileLocatorUploadBean.java

/**
 * Executes a HEAD request to the locator.
 * //from   w w  w .  ja v  a 2s .  com
 * @param locator
 * @return true if locator is accessible
 */
public boolean checkLocator(String locator) {
    this.locator = locator;
    if (locator != null) {
        this.locator = this.locator.trim();
    }
    URLConnection conn = null;
    byte[] input = null;
    String mimeType = null;
    String fileName = null;
    URL locatorURL = null;

    try {
        locatorURL = new URL(locator);
        conn = locatorURL.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 302:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 200:
            this.logger.debug("Source responded with 200.");
            break;
        case 403:
            this.error = getMessage("errorLocatorAccessDenied");
            this.logger.warn("Access to url " + locator + " is restricted.");
            return false;
        default:
            this.error = getMessage("errorLocatorTechnicalException");
            this.logger.warn("An error occurred during importing from external system: " + responseCode + ": "
                    + httpConn.getResponseMessage() + ".");
            return false;
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        this.error = getMessage("errorLocatorAccessDenied");
        return false;
    } catch (MalformedURLException e) {
        this.error = getMessage("errorLocatorInvalidURL");
        this.logger.warn("Invalid locator URL:" + locator, e);
        return false;
    } catch (Exception e) {
        this.error = getMessage("errorLocatorTechnicalException");
        return false;
    }

    // Get Content Type
    mimeType = conn.getHeaderField("Content-Type");
    if (mimeType.contains(";")) {
        mimeType = mimeType.substring(0, mimeType.indexOf(";"));
    }
    if (mimeType != null) {
        this.setType(mimeType);
    }
    // Get File Name
    fileName = conn.getHeaderField("file-name");
    if (fileName != null) {
        this.setName(fileName);
    } else {
        this.setName(locatorURL.toString());
    }
    // Get File Length
    try {
        this.setSize(Integer.parseInt(conn.getHeaderField("Content-Length")));
    } catch (NumberFormatException e) {
        input = this.fetchLocator(locatorURL);
        if (input != null) {
            this.setSize(input.length);
        }
    }
    return true;
}

From source file:de.mpg.escidoc.pubman.util.FileLocatorUploadBean.java

/**
 * Executes a HEAD request to the locator.
 * /*w  w  w.j a  va  2 s . c  o  m*/
 * @param locator
 * @return true if locator is accessible
 */
public boolean checkLocator(String locator) {
    this.locator = locator;
    if (locator != null) {
        this.locator = this.locator.trim();
    }
    URLConnection conn = null;
    byte[] input = null;
    String mimeType = null;
    String fileName = null;
    URL locatorURL = null;

    try {
        locatorURL = new URL(locator);
        conn = locatorURL.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 302:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 200:
            this.logger.debug("Source responded with 200.");
            break;
        case 403:
            this.error = getMessage("errorLocatorAccessDenied");
            this.logger.warn("Access to url " + locator + " is restricted.");
            return false;
        default:
            this.error = getMessage("errorLocatorTechnicalException");
            this.logger.warn("An error occurred during importing from external system: " + responseCode + ": "
                    + httpConn.getResponseMessage() + ".");
            return false;
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        this.error = getMessage("errorLocatorAccessDenied");
        return false;
    } catch (MalformedURLException e) {
        this.error = getMessage("errorLocatorInvalidURL");
        this.logger.warn("Invalid locator URL:" + locator, e);
        return false;
    } catch (Exception e) {
        this.error = getMessage("errorLocatorTechnicalException");
        return false;
    }

    //Get Content Type
    mimeType = conn.getHeaderField("Content-Type");
    if (mimeType.contains(";")) {
        mimeType = mimeType.substring(0, mimeType.indexOf(";"));
    }
    if (mimeType != null) {
        this.setType(mimeType);
    }
    //Get File Name
    fileName = conn.getHeaderField("file-name");
    if (fileName != null) {
        this.setName(fileName);
    } else {
        this.setName(locatorURL.toString());
    }
    //Get File Length
    try {
        this.setSize(Integer.parseInt(conn.getHeaderField("Content-Length")));
    } catch (NumberFormatException e) {
        input = this.fetchLocator(locatorURL);
        if (input != null) {
            this.setSize(input.length);
        }
    }
    return true;
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

/**
 * Apply normalization rules to the identifier supplied by the End-User 
 * to determine the Resource and Host. Then make an HTTP GET request to
 * the host's WebFinger endpoint to obtain the location of the requested 
 * service//from  w  w w.j  a v a 2  s. c o  m
 * return the issuer location ("href")
 * @param user_input , domain
 * @return
 */

public static String webfinger(String userInput, String serverUrl) {
    // android.os.Debug.waitForDebugger();

    String result = ""; // result of the http request (a json object
    // converted to string)
    String postUrl = "";
    String host = null;
    String href = null;

    // URI identifying the type of service whose location is being requested
    final String rel = "http://openid.net/specs/connect/1.0/issuer";

    if (!isEmpty(userInput)) {

        try {
            // normalizes this URI's path
            URI uri = new URI(userInput).normalize();
            String[] parts = uri.getRawSchemeSpecificPart().split("@");

            if (!isEmpty(serverUrl)) {
                // use serverUrl if specified
                if (serverUrl.startsWith("https://")) {
                    host = serverUrl.substring(8);
                } else if (serverUrl.startsWith("http://")) {
                    host = serverUrl.substring(7);
                } else {
                    host = serverUrl;
                }
            } else if (parts.length > 1) {
                // the user is using an E-Mail Address Syntax
                host = parts[parts.length - 1];
            } else {
                // the user is using an other syntax
                host = uri.getHost();
            }

            // check if host is valid
            if (host == null) {
                return null;
            }

            if (!host.endsWith("/"))
                host += "/";
            postUrl = "https://" + host + ".well-known/webfinger?resource=" + userInput + "&rel=" + rel;

            // log the request
            Logd(TAG, "Web finger request\n GET " + postUrl + "\n HTTP /1.1" + "\n Host: " + host);
            // Send an HTTP get request with the resource and rel parameters
            HttpURLConnection huc = getHUC(postUrl);
            huc.setDoOutput(true);
            huc.setRequestProperty("Content-Type", "application/jrd+json");
            huc.connect();

            try {

                int responseCode = huc.getResponseCode();
                Logd(TAG, "webfinger responseCode: " + responseCode);
                // if 200, read http body
                if (responseCode == 200) {
                    InputStream is = huc.getInputStream();
                    result = convertStreamToString(is);
                    is.close();
                    Logd(TAG, "webfinger result: " + result);

                    // The response is a json object and the issuer location
                    // is returned as the value of the href member
                    // a links array element with the rel member value
                    // http://openid.net/specs/connect/1.0/issuer
                    JSONObject jo = new JSONObject(result);
                    JSONObject links = jo.getJSONArray("links").getJSONObject(0);
                    href = links.getString("href");
                    Logd(TAG, "webfinger reponse href: " + href);

                } else {
                    // why the request didn't succeed
                    href = huc.getResponseMessage();
                }

                // close connection
                huc.disconnect();
            } catch (IOException ioe) {
                Logd(TAG, "webfinger io exception: " + huc.getErrorStream());
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        // the user_input is empty
        href = "no identifier detected!!\n";
    }
    return href;
}

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

JSONObject requestFeed(long from) throws IOException, JSONException {
    URL newurl = new URL(FEED_URL);
    HttpURLConnection conn = (HttpURLConnection) newurl.openConnection();
    conn.setDoOutput(true);//from   ww w  .  j  a va  2  s.co  m
    conn.setRequestMethod(RequestMethod.POST.name());
    conn.addRequestProperty("Authorization", "Bearer " + feed_access_token);

    FormValues kv = new FormValues();
    kv.put("lastPostTime", Long.toString(from));
    kv.put("feedItemTypes", FEED_ITEM_TYPES);

    {
        OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
        kv.write(wr);
        wr.flush();
        wr.close();
    }

    int responseCode = conn.getResponseCode();
    String amsg = conn.getResponseMessage();
    InputStream in = new BufferedInputStream(conn.getInputStream());
    JSONObject obj = SyncHelper.parse(in);

    conn.disconnect();
    if (responseCode == HttpStatus.SC_OK) {
        return obj;
    }
    throw new IOException(amsg);
}

From source file:com.example.android.network.sync.basicsyncadapter.SyncAdapter.java

/**
 * Given a string representation of a URL, sets up a connection and gets an input stream.
 *///from w  ww.j  av  a2  s . co m
private SyncResult doFetchAllForURL(Class sClass, SyncResult sResults) throws IOException {

    try {
        Method urlForFetchAllMethod = sClass.getDeclaredMethod("urlForFetchAll", null);
        String urlForFetchAll = (String) urlForFetchAllMethod.invoke(null, null);

        System.out.println(urlForFetchAll);
        final URL fetchAllURL = new URL(urlForFetchAll);

        HttpURLConnection conn = (HttpURLConnection) fetchAllURL.openConnection();
        conn.setRequestProperty("X-Parse-Application-Id", "TsEDR12ICJtD59JM92WslVurN0wh5JPuznKvroRc");
        conn.setRequestProperty("X-Parse-REST-API-Key", "4LC6oFNCyqLMFHSdPIPsxJoXHY6gTHGMG2kUcbwB");
        conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
        conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        Log.i(TAG, "Response from parse.com : " + conn.getResponseMessage());
        Log.i(TAG, "Status Code from parse.com : " + conn.getResponseCode());

        Class[] cArg = new Class[3];
        cArg[0] = Context.class;
        cArg[1] = InputStream.class;
        cArg[2] = SyncResult.class;

        Method handleDataForModel = sClass.getDeclaredMethod("handleInsertWithData", cArg);
        SyncResult objectsUpdated = (SyncResult) handleDataForModel.invoke(null, this.getContext(),
                conn.getInputStream(), sResults);
        return objectsUpdated;
    }

    catch (Exception ex) {
        Log.i(TAG, "exception " + ex.toString());
    }

    return sResults;
}