Java Code Examples for java.net.HttpURLConnection#HTTP_ACCEPTED

The following examples show how to use java.net.HttpURLConnection#HTTP_ACCEPTED . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   File: ChunkedUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get an input stream containing the partial response if one is present.
 *
 * @param connection the connection in question
 * @param responseCode the response code
 * @return an input stream if a partial response is pending on the connection
 */
public static InputStream getPartialResponse(
    HttpURLConnection connection,
    int responseCode
) throws IOException {
    InputStream in = null;
    if (responseCode == HttpURLConnection.HTTP_ACCEPTED
        || responseCode == HttpURLConnection.HTTP_OK) {
        if (connection.getContentLength() > 0) {
            in = connection.getInputStream();
        } else if (hasChunkedResponse(connection)
                   || hasEofTerminatedResponse(connection)) {
            // ensure chunked or EOF-terminated response is non-empty
            in = getNonEmptyContent(connection);
        }
    }
    return in;
}
 
Example 2
private void performCloseOverHttp(String urlSuffix, String defaultResponse) {
    Configuration configuration = Utils.getConfiguration(password);
    HttpClient httpClient = new HttpClient(configuration);
    HttpRequest httpRequest = new HttpRequest(urlSuffix);

    // do DELETE
    HttpResponse response = httpClient.sendHttpRequest(httpRequest, HTTP_DELETE);

    // handle response
    if (response.getStatusCode() == HttpURLConnection.HTTP_ACCEPTED) {
        Message message = buildResponseMessage(response, defaultResponse);
        ResponseFormatter.printMessage(message);
    } else {
        ResponseFormatter.handleErrorResponse(buildResponseMessage(response, BROKER_ERROR_MSG));
    }
}
 
Example 3
Source Project: pre-dem-android   File: DEMImpl.java    License: MIT License 6 votes vote down vote up
private boolean sendRequest(String url, String content) {
        LogUtils.d(TAG, "----url:" + url + "\tcontent:" + content);
        try {
            HttpURLConnection httpConn = new HttpURLConnectionBuilder(url)
                    .setRequestMethod("POST")
                    .setHeader("Content-Type", "application/json")
                    .setRequestBody(content)
                    .build();

            int responseCode = httpConn.getResponseCode();
            boolean successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
            return successful;
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
    }
 
Example 4
@Override
public void close() throws IOException {
    try {
        if (writer != null) {
            writer.close();
        }
    } catch (IOException e) {
        LOG.error("Error closing writer", e);
    } finally {
        this.writer = null;
        this.exporter = null;
    }

    int response = connection.getResponseCode();
    if (response != HttpURLConnection.HTTP_ACCEPTED) {
        throw new IOException("Response code from " + url + " was " + response);
    }
    connection.disconnect();
    this.connection = null;
}
 
Example 5
Source Project: ant-ivy   File: AbstractURLHandler.java    License: Apache License 2.0 6 votes vote down vote up
protected void validatePutStatusCode(URL dest, int statusCode, String statusMessage)
        throws IOException {
    switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_CREATED:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_ACCEPTED:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_NO_CONTENT:
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new IOException("Access to URL " + dest + " was refused by the server"
                    + (statusMessage == null ? "" : ": " + statusMessage));
        default:
            throw new IOException("PUT operation to URL " + dest + " failed with status code "
                    + statusCode + (statusMessage == null ? "" : ": " + statusMessage));
    }
}
 
Example 6
Source Project: cxf   File: NettyHttpConduit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream getPartialResponse() throws IOException {
    InputStream in = null;
    int responseCode = getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_ACCEPTED
            || responseCode == HttpURLConnection.HTTP_OK) {

        String head = httpResponse.headers().get(HttpHeaderHelper.CONTENT_LENGTH);
        int cli = 0;
        if (head != null) {
            cli = Integer.parseInt(head);
        }
        head = httpResponse.headers().get(HttpHeaderHelper.TRANSFER_ENCODING);
        boolean isChunked = head != null &&  HttpHeaderHelper.CHUNKED.equalsIgnoreCase(head);
        head = httpResponse.headers().get(HttpHeaderHelper.CONNECTION);
        boolean isEofTerminated = head != null &&  HttpHeaderHelper.CLOSE.equalsIgnoreCase(head);
        if (cli > 0) {
            in = getInputStream();
        } else if (isChunked || isEofTerminated) {
            // ensure chunked or EOF-terminated response is non-empty
            try {
                PushbackInputStream pin =
                        new PushbackInputStream(getInputStream());
                int c = pin.read();
                if (c != -1) {
                    pin.unread((byte)c);
                    in = pin;
                }
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
    return in;
}
 
Example 7
Source Project: yandex-money-sdk-java   File: FirstApiRequest.java    License: MIT License 5 votes vote down vote up
@Override
public final T parse(HttpClientResponse response) throws Exception {
    InputStream inputStream = null;

    try {
        switch (response.getCode()) {
            case HttpURLConnection.HTTP_OK:
            case HttpURLConnection.HTTP_ACCEPTED:
            case HttpURLConnection.HTTP_BAD_REQUEST:
                inputStream = response.getByteStream();
                if (isJsonType(response)) {
                    return Responses.parseJson(inputStream, cls, typeAdapter);
                } else {
                    throw new InvalidRequestException(processError(response));
                }
            case HttpURLConnection.HTTP_UNAUTHORIZED:
                throw new InvalidTokenException(processError(response));
            case HttpURLConnection.HTTP_FORBIDDEN:
                throw new InsufficientScopeException(processError(response));
            default:
                throw new IOException(processError(response));
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}
 
Example 8
private void sendMessage(String url, Message msg, MimeBodyPart securedData, String retries) throws Exception {
    URL urlObj = new URL(url);
    InternetHeaders ih = getHttpHeaders(msg, securedData);
    msg.setAttribute(NetAttribute.MA_DESTINATION_IP, urlObj.getHost());
    msg.setAttribute(NetAttribute.MA_DESTINATION_PORT, Integer.toString(urlObj.getPort()));

    if (logger.isInfoEnabled()) {
        logger.info("Connecting to: " + url + msg.getLogMsgID());
    }

    Map<String, String> httpOptions = getHttpOptions();
    httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
    httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
    long maxSize = msg.getPartnership().getNoChunkedMaxSize();
    ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, ih.getAllHeaders(), null, securedData.getInputStream(), httpOptions, maxSize);
    if (logger.isInfoEnabled()) {
        logger.info("Message sent and response received in " + resp.getTransferTimeMs() + "ms" + msg.getLogMsgID());
    }

    // Check the HTTP Response code
    int rc = resp.getStatusCode();
    if ((rc != HttpURLConnection.HTTP_OK) && (rc != HttpURLConnection.HTTP_CREATED) && (rc != HttpURLConnection.HTTP_ACCEPTED) && (rc != HttpURLConnection.HTTP_PARTIAL) && (rc != HttpURLConnection.HTTP_NO_CONTENT)) {
        msg.setLogMsg("Error sending message. URL: " + url + " ::: Response Code: " + rc + " " + resp.getStatusPhrase() + " ::: Response Message: " + resp.getBody().toString());
        logger.error(msg);
        throw new HttpResponseException(url, rc, resp.getStatusPhrase());
    }
    // So far so good ...
    processResponse(msg, resp);
}
 
Example 9
public void testRequestWasSuccessful_successfulStatusCodes() {
  final int[] statusCodes = {
    HttpURLConnection.HTTP_OK,
    HttpURLConnection.HTTP_CREATED,
    HttpURLConnection.HTTP_ACCEPTED,
    HttpURLConnection.HTTP_NOT_AUTHORITATIVE
  };
  for (int statusCode : statusCodes) {
    assertTrue(defaultSettingsSpiCall.requestWasSuccessful(statusCode));
  }
}
 
Example 10
private void checkStatusCode(InputStream in, HttpClientTransport con) throws IOException {
    int statusCode = con.statusCode;
    String statusMessage = con.statusMessage;
    // SOAP1.1 and SOAP1.2 differ here
    if (binding instanceof SOAPBinding) {
        if (binding.getSOAPVersion() == SOAPVersion.SOAP_12) {
            //In SOAP 1.2, Fault messages can be sent with 4xx and 5xx error codes
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || isErrorCode(statusCode)) {
                // acceptable status codes for SOAP 1.2
                if (isErrorCode(statusCode) && in == null) {
                    // No envelope for the error, so throw an exception with http error details
                    throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
                }
                return;
            }
        } else {
            // SOAP 1.1
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                // acceptable status codes for SOAP 1.1
                if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR && in == null) {
                    // No envelope for the error, so throw an exception with http error details
                    throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
                }
                return;
            }
        }
        if (in != null) {
            in.close();
        }
        throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
    }
    // Every status code is OK for XML/HTTP
}
 
Example 11
Source Project: cxf   File: HTTPConduitURLEasyMockTest.java    License: Apache License 2.0 5 votes vote down vote up
private int getResponseCode(ResponseStyle style) {
    int code;
    if (style == ResponseStyle.BACK_CHANNEL) {
        code = HttpURLConnection.HTTP_OK;
    } else if (style == ResponseStyle.BACK_CHANNEL_ERROR) {
        code = HttpURLConnection.HTTP_BAD_REQUEST;
    } else {
        code = HttpURLConnection.HTTP_ACCEPTED;
    }
    return code;
}
 
Example 12
private void checkStatusCode(InputStream in, HttpClientTransport con) throws IOException {
    int statusCode = con.statusCode;
    String statusMessage = con.statusMessage;
    // SOAP1.1 and SOAP1.2 differ here
    if (binding instanceof SOAPBinding) {
        if (binding.getSOAPVersion() == SOAPVersion.SOAP_12) {
            //In SOAP 1.2, Fault messages can be sent with 4xx and 5xx error codes
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || isErrorCode(statusCode)) {
                // acceptable status codes for SOAP 1.2
                if (isErrorCode(statusCode) && in == null) {
                    // No envelope for the error, so throw an exception with http error details
                    throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
                }
                return;
            }
        } else {
            // SOAP 1.1
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                // acceptable status codes for SOAP 1.1
                if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR && in == null) {
                    // No envelope for the error, so throw an exception with http error details
                    throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
                }
                return;
            }
        }
        if (in != null) {
            in.close();
        }
        throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
    }
    // Every status code is OK for XML/HTTP
}
 
Example 13
Source Project: hadoop   File: AuthenticatedURL.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 14
Source Project: big-c   File: AuthenticatedURL.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 15
private void checkStatusCode(InputStream in, HttpClientTransport con) throws IOException {
    int statusCode = con.statusCode;
    String statusMessage = con.statusMessage;
    // SOAP1.1 and SOAP1.2 differ here
    if (binding instanceof SOAPBinding) {
        if (binding.getSOAPVersion() == SOAPVersion.SOAP_12) {
            //In SOAP 1.2, Fault messages can be sent with 4xx and 5xx error codes
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || isErrorCode(statusCode)) {
                // acceptable status codes for SOAP 1.2
                if (isErrorCode(statusCode) && in == null) {
                    // No envelope for the error, so throw an exception with http error details
                    throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
                }
                return;
            }
        } else {
            // SOAP 1.1
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                // acceptable status codes for SOAP 1.1
                if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR && in == null) {
                    // No envelope for the error, so throw an exception with http error details
                    throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
                }
                return;
            }
        }
        if (in != null) {
            in.close();
        }
        throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
    }
    // Every status code is OK for XML/HTTP
}
 
Example 16
/**
 * Validate the http response.
 *
 * @param statusCode status code
 * @return boolean to validate response
 */
private boolean responseValidate(int statusCode, String response) {
  boolean isValid = false;
  switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
      isValid = true;
      break;
    case HttpURLConnection.HTTP_CREATED:
      isValid = true;
      break;
    case HttpURLConnection.HTTP_ACCEPTED:
      isValid = true;
      break;
    case HttpURLConnection.HTTP_BAD_REQUEST:
      if (response != null && !Constants.Utils.EMPTY_STRING.equals(response)) {
        if (response.contains(Constants.Utils.DIFFERENT_CONTEXT_ERROR)
            || response.contains(Constants.Utils.DUPLICATE_CONTEXT_ERROR)) {
          // skip the error when trying to add the same api with different context.
          isValid = true;
        }
      }
      break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
      isValid = false;
      break;
    case HttpURLConnection.HTTP_NOT_FOUND:
      isValid = false;
      break;
    case HttpURLConnection.HTTP_CONFLICT:
      if (response != null && !Constants.Utils.EMPTY_STRING.equals(response)) {
        if (response.contains(Constants.Utils.DUPLICATE_API_ERROR)) {
          // skip the error when trying to add the same api.
          isValid = true;
        }
      }
      break;
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
      if (response != null && !Constants.Utils.EMPTY_STRING.equals(response)) {
        if (response.contains(Constants.Utils.DUPLICATE_LABEL_ERROR)) {
          // skip the error when trying to add the same label.
          isValid = true;
        }
      }
      break;
    default:
      isValid = false;
  }
  return isValid;
}
 
Example 17
/**
 * Validate the http response.
 * @param statusCode status code
 * @return boolean to validate response
 */
private boolean responseValidate(int statusCode, String response) throws IOException {
    boolean isValid = false;
    switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
            isValid = true;
            break;
        case HttpURLConnection.HTTP_CREATED:
            isValid = true;
            break;
        case HttpURLConnection.HTTP_ACCEPTED:
            isValid = true;
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            if (response != null && !Constants.Utils.EMPTY_STRING.equals(response)) {
                if (response.contains(Constants.Utils.DIFFERENT_CONTEXT_ERROR) ||
                    response.contains(Constants.Utils.DUPLICATE_CONTEXT_ERROR)) {
                    // skip the error when trying to add the same api with different context.
                    isValid = true;
                }
            }
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            isValid = false;
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            isValid = false;
            break;
        case HttpURLConnection.HTTP_CONFLICT:
            if (response != null && !Constants.Utils.EMPTY_STRING.equals(response)) {
                if (response.contains(Constants.Utils.DUPLICATE_API_ERROR)) {
                    // skip the error when trying to add the same api.
                    isValid = true;
                }
            }
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            if (response != null && !Constants.Utils.EMPTY_STRING.equals(response)) {
                if (response.contains(Constants.Utils.DUPLICATE_LABEL_ERROR)) {
                    // skip the error when trying to add the same label.
                    isValid = true;
                }
            }
            break;
        default:
            isValid = false;
    }
    return isValid;
}
 
Example 18
Source Project: pre-dem-android   File: PrintLogger.java    License: MIT License 4 votes vote down vote up
private void report(String filename, String key) {
        //3、上报服务器
        HttpURLConnection url = null;
        boolean successful = false;
        try {
            JSONObject parameters = new JSONObject();

            parameters.put("app_bundle_id", AppBean.APP_PACKAGE);
            parameters.put("app_name", AppBean.APP_NAME);
            parameters.put("app_version", AppBean.APP_VERSION);
            parameters.put("device_model", AppBean.PHONE_MODEL);
            parameters.put("os_platform", AppBean.ANDROID_PLATFORM);
            parameters.put("os_version", AppBean.ANDROID_VERSION);
            parameters.put("os_build", AppBean.ANDROID_BUILD);
            parameters.put("sdk_version", AppBean.SDK_VERSION);
            parameters.put("sdk_id", AppBean.SDK_ID);
            parameters.put("device_id", AppBean.DEVICE_IDENTIFIER);
            parameters.put("tag", AppBean.APP_TAG);
            parameters.put("manufacturer", AppBean.PHONE_MANUFACTURER);
            parameters.put("start_time", mStartTime);
            parameters.put("end_time", mEndTime);
            parameters.put("log_key", key);
            parameters.put("log_tags", "");
            parameters.put("error_count", 0);

            url = new HttpURLConnectionBuilder(Configuration.getLogcatUrl())
                    .setRequestMethod("POST")
                    .setHeader("Content-Type", "application/json")
                    .setRequestBody(parameters.toString())
                    .build();

            int responseCode = url.getResponseCode();

            successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
        } catch (Exception e) {
            LogUtils.e(TAG, "----" + e.toString());
//            e.printStackTrace();
        } finally {
            if (url != null) {
                url.disconnect();
            }
            if (successful) {
                mContext.deleteFile(filename);
            } else {
                LogUtils.d("-----Transmission failed, will retry on next register() call");
            }
        }
    }
 
Example 19
Source Project: Sentry-Android   File: Sentry.java    License: MIT License 4 votes vote down vote up
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
Example 20
public JamNetworkResult GetRequestWithResult(final String urlString, final JamNetworkParam params) {
    JamNetworkResult result = null;
    try {
        System.out.println("\n       [GET][TOKEN:"+currentOAuthToken+"] Sending 'GET' request to URL : " + urlString);

        // Create a get GET url request with Authorization header
        final HttpURLConnection con = createConnection(urlString, "GET", currentProxy);

        if (currentOAuthToken != null) {
            con.setRequestProperty("Authorization", "OAuth " + currentOAuthToken);
        }

        System.out.println("      Header:");
        for (final Map.Entry<String, String> entry : params.getParams().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            System.out.println("          " + key + " : " + value);
            con.setRequestProperty(key, value);
        }

        // Read response and parse to JSON
        final int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
            || responseCode == HttpURLConnection.HTTP_ACCEPTED) {

            result = new JamNetworkResult();
            result.inputStream = con.getInputStream();
        } else {
            // If it's an error, output the error to console
            System.out.println("      Failure: Server's code: " + responseCode + " with the following error");
            final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("        " + line);
            }
        }
    } catch (final Exception e) {
        throw new RuntimeException("Exception while making Get URL Request:" + e.toString(), e);
    }

    return result;
}