Java Code Examples for java.net.HttpURLConnection.getResponseMessage()

The following are Jave code examples for showing how to use getResponseMessage() of the java.net.HttpURLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: AndroidProgramming3e   File: FlickrFetchr.java   Source Code and License Vote up 6 votes
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 2
Project: rapidminer   File: MarketplaceUpdateManager.java   Source Code and License Vote up 6 votes
private boolean compareMD5(File toCompare, String urlString) {
    if(urlString != null && toCompare != null && !urlString.equals("")) {
        try {
            String e = getMD5hash(toCompare);
            URL url = getUpdateServerURI(urlString).toURL();
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            WebServiceTools.setURLConnectionDefaults(con);
            con.setDoInput(true);
            con.setDoOutput(false);

            String serverMD5;
            try {
                serverMD5 = this.getServerMD5(con.getInputStream());
            } catch (IOException var8) {
                throw new IOException(con.getResponseCode() + ": " + con.getResponseMessage(), var8);
            }

            return serverMD5.compareTo(e) == 0;
        } catch (Exception var9) {
            return false;
        }
    } else {
        throw new IllegalArgumentException("parameter is empty");
    }
}
 
Example 3
Project: AndroidProgramming3e   File: FlickrFetchr.java   Source Code and License Vote up 6 votes
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 4
Project: AndroidProgramming3e   File: FlickrFetchr.java   Source Code and License Vote up 6 votes
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 5
Project: Android-Programming-BigNerd   File: FlickrFetchr.java   Source Code and License Vote up 6 votes
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() + ": with " +
                    urlSpec);
        }
        
        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 6
Project: AndroidProgramming3e   File: FlickrFetchr.java   Source Code and License Vote up 6 votes
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 7
Project: AndroidPracticalSamples   File: HttpClient.java   Source Code and License Vote up 6 votes
public static byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() + ": with " + urlSpec);
        }

        int bytesRead = 0;
        byte[] buffer = new byte[1024];

        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 8
Project: openmensa-java   File: OpenMensaOrg.java   Source Code and License Vote up 6 votes
public String queryAPI(String query) throws IOException {
    URL url = new URL(API_URL + query);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new IOException("Server responded with: " + responseCode + " " + connection.getResponseMessage());
    }

    InputStream input = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    input.close();
    return response.toString();
}
 
Example 9
Project: EsperantoRadio   File: Diverse.java   Source Code and License Vote up 6 votes
public static String hentUrlSomStreng(String url) throws IOException {
  Log.d("hentUrlSomStreng lgd=" + url.length() + "  " + url);

  URL u = new URL(url);
  HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection();
  urlConnection.setConnectTimeout(15000);
  urlConnection.setReadTimeout(90 * 1000);   // 1 1/2 minut
  urlConnection.setInstanceFollowRedirects(true);
  urlConnection.connect(); // http://stackoverflow.com/questions/8179658/urlconnection-getcontent-return-null
  InputStream is = urlConnection.getInputStream();
  Log.d("åbnGETURLConnection url.length()=" + url.length() + "  is=" + is + "  is.available()=" + is.available());
  if (urlConnection.getResponseCode() != 200)
    throw new IOException("HTTP-svar var " + urlConnection.getResponseCode() + " " + urlConnection.getResponseMessage() + " for " + u);

  tjekOmdirigering(u, urlConnection);

  return læsStreng(is);
}
 
Example 10
Project: gitea-plugin   File: DefaultGiteaConnection.java   Source Code and License Vote up 5 votes
@Override
public boolean checkFile(GiteaRepository repository, String ref, String path)
        throws IOException, InterruptedException {
    HttpURLConnection connection = (HttpURLConnection) new URL(
            api()
                    .literal("/repos")
                    .path(UriTemplateBuilder.var("username"))
                    .path(UriTemplateBuilder.var("name"))
                    .literal("/raw")
                    .path(UriTemplateBuilder.var("ref", true))
                    .path(UriTemplateBuilder.var("path", true))
                    .build()
                    .set("username", repository.getOwner().getUsername())
                    .set("name", repository.getName())
                    .set("ref", StringUtils.split(ref, '/'))
                    .set("path", StringUtils.split(path, "/"))
                    .expand()
    ).openConnection();
    withAuthentication(connection);
    try {
        connection.connect();
        int status = connection.getResponseCode();
        if (status == 404) {
            return false;
        }
        if (status / 100 == 2) {
            return true;
        }
        throw new IOException("HTTP " + status + "/" + connection.getResponseMessage());
    } finally {
        connection.disconnect();
    }
}
 
Example 11
Project: android-tv-news   File: RSSReader.java   Source Code and License Vote up 5 votes
/**
 * Send HTTP GET request and parse the XML response to construct an in-memory
 * representation of an RSS 2.0 feed.
 *
 * @param uri RSS 2.0 feed URI
 * @return in-memory representation of downloaded RSS feed
 * @throws RSSReaderException if RSS feed could not be retrieved because of
 *           HTTP error
 * @throws RSSFault if an unrecoverable IO error has occurred
 */
public RSSFeed load(String uri) throws RSSReaderException {
    InputStream feedStream = null;
    try {
        URL url = new URL(uri);
        // Send GET request to URI
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.connect();

        // Check if server response is valid
        if (conn.getResponseCode() != 200) {
            throw new RSSReaderException(conn.getResponseCode(),
                    conn.getResponseMessage());
        }

        // Extract content stream from HTTP response
        feedStream = conn.getInputStream();
        RSSFeed feed = parser.parse(feedStream);

        if (feed.getLink() == null) {
            feed.setLink(android.net.Uri.parse(uri));
        }

        return feed;
    } catch (IOException e) {
        throw new RSSFault(e);
    } finally {
        Resources.closeQuietly(feedStream);
    }
}
 
Example 12
Project: boohee_v5.6   File: HurlStack.java   Source Code and License Vote up 5 votes
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());
    map.putAll(additionalHeaders);
    if (this.mUrlRewriter != null) {
        String rewritten = this.mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    HttpURLConnection connection = openConnection(new URL(url), request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, (String) map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    if (connection.getResponseCode() == -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);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            response.addHeader(new BasicHeader((String) header.getKey(), (String) ((List) header.getValue()).get(0)));
        }
    }
    return response;
}
 
Example 13
Project: GeekZone   File: BaseStack.java   Source Code and License Vote up 5 votes
@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);
    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;
}
 
Example 14
Project: gitea-plugin   File: DefaultGiteaConnection.java   Source Code and License Vote up 5 votes
private <T> T post(UriTemplate template, Object body, final Class<T> modelClass)
        throws IOException, InterruptedException {
    HttpURLConnection connection = (HttpURLConnection) new URL(template.expand()).openConnection();
    withAuthentication(connection);
    connection.setRequestMethod("POST");
    byte[] bytes;
    if (body != null) {
        bytes = mapper.writer(new ISO8601DateFormat()).writeValueAsBytes(body);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        connection.setDoOutput(true);
    } else {
        bytes = null;
        connection.setDoOutput(false);
    }
    connection.setDoInput(!Void.class.equals(modelClass));

    try {
        connection.connect();
        if (bytes != null) {
            try (OutputStream os = connection.getOutputStream()) {
                os.write(bytes);
            }
        }
        int status = connection.getResponseCode();
        if (status / 100 == 2) {
            if (Void.class.equals(modelClass)) {
                return null;
            }
            try (InputStream is = connection.getInputStream()) {
                return mapper.readerFor(modelClass).readValue(is);
            }
        }
        throw new IOException(
                "HTTP " + status + "/" + connection.getResponseMessage() + "\n" + (bytes != null ? new String(bytes,
                        StandardCharsets.UTF_8) : ""));
    } finally {
        connection.disconnect();
    }
}
 
Example 15
Project: hadoop   File: AuthenticatedURL.java   Source Code and License Vote up 5 votes
/**
 * Helper method that extracts an authentication token received from a connection.
 * <p>
 * This method is used by {@link Authenticator} implementations.
 *
 * @param conn connection to extract the authentication token from.
 * @param token the authentication token.
 *
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication exception occurred.
 */
public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException {
  int respCode = conn.getResponseCode();
  if (respCode == HttpURLConnection.HTTP_OK
      || respCode == HttpURLConnection.HTTP_CREATED
      || respCode == HttpURLConnection.HTTP_ACCEPTED) {
    Map<String, List<String>> headers = conn.getHeaderFields();
    List<String> cookies = headers.get("Set-Cookie");
    if (cookies != null) {
      for (String cookie : cookies) {
        if (cookie.startsWith(AUTH_COOKIE_EQ)) {
          String value = cookie.substring(AUTH_COOKIE_EQ.length());
          int separator = value.indexOf(";");
          if (separator > -1) {
            value = value.substring(0, separator);
          }
          if (value.length() > 0) {
            token.set(value);
          }
        }
      }
    }
  } else {
    token.set(null);
    throw new AuthenticationException("Authentication failed, status: " + conn.getResponseCode() +
                                      ", message: " + conn.getResponseMessage());
  }
}
 
Example 16
Project: BittrexApi   File: UrlConnectionDownloader.java   Source Code and License Vote up 5 votes
@Override
public Response execute(@NonNull Request request) throws IOException {
    Ensure.isNotNull("request", request);

    final HttpURLConnection connection = openConnection(Uri.parse(request.url()));
    connection.setUseCaches(false);

    connection.addRequestProperty(HttpHeader.Accept, "application/json");
    connection.addRequestProperty(HttpHeader.CacheControl, "no-cache, no-store, must-revalidate");

    for (NameValuePair header : request.headers()) {
        connection.addRequestProperty(header.name(), header.value());
    }

    int responseCode = connection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
        connection.disconnect();
        throw new ResponseException(responseCode + " " + connection.getResponseMessage(), responseCode);
    }

    final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
    final StringBuilder stringBuilder = new StringBuilder();

    String currentLine;

    while ((currentLine = bufferedReader.readLine()) != null) {
        stringBuilder.append(currentLine);
    }

    return new Response(stringBuilder.toString(), responseCode);
}
 
Example 17
Project: airgram   File: HurlStack.java   Source Code and License Vote up 5 votes
@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);
    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;
}
 
Example 18
Project: cloud-c4c-ticket-duplicate-finder-ext   File: HTTPConnector.java   Source Code and License Vote up 5 votes
private SimpleHttpResponse executeMethodGET(HttpURLConnection urlConnection) throws IOException, InvalidResponseException {
	SimpleHttpResponse httpResponse = new SimpleHttpResponse(urlConnection.getURL().toString(), urlConnection.getResponseCode(),
			urlConnection.getResponseMessage());
	httpResponse.setContentType(urlConnection.getContentType());
	httpResponse.setContent(IOUtils.toString(urlConnection.getInputStream()));
	logResponse(httpResponse);
	validateResponse(httpResponse);
	return httpResponse;
}
 
Example 19
Project: PlusGram   File: HurlStack.java   Source Code and License Vote up 4 votes
@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);
    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;
}
 
Example 20
Project: Codeforces   File: HurlStack.java   Source Code and License Vote up 4 votes
@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);
    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;
}