List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.netflix.genie.server.util.NetUtil.java
/** * Returns the response from an HTTP GET call if it succeeds, null * otherwise./*from w ww .j a va2s. c om*/ * * @param uri The URI to execute the HTTP GET on * @return response from an HTTP GET call if it succeeds, null otherwise * @throws IOException if there was an error with the HTTP request */ private static String httpGet(final String uri) throws IOException { String response = null; //TODO: Use one of other http clients to remove dependency final HttpClient client = new HttpClient(); final HttpMethod method = new GetMethod(uri); client.executeMethod(method); final int status = method.getStatusCode(); if (status == HttpURLConnection.HTTP_OK) { response = method.getResponseBodyAsString(); } return response; }
From source file:com.adaptris.http.HttpClientTransport.java
/** * Is the HTTP response code considered to be a success. * <p>/*from w w w. j a va 2 s .co m*/ * There are 7 possible HTTP codes that signify success or partial success :- * <code>200,201,202,203,204,205,206</code> * </p> * * @return true if the transaction was successful. */ private boolean wasSuccessful(HttpSession session) { boolean rc = false; switch (session.getResponseLine().getResponseCode()) { case HttpURLConnection.HTTP_ACCEPTED: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_NO_CONTENT: case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_PARTIAL: case HttpURLConnection.HTTP_RESET: { rc = true; break; } default: { rc = false; break; } } return rc; }
From source file:com.arcbees.vcs.AbstractVcsApi.java
private HttpResponse doExecuteRequest(HttpClientWrapper httpClient, HttpUriRequest request, Credentials credentials) throws IOException { includeAuthentication(request, credentials); setDefaultHeaders(request);/*from w w w .ja v a2 s. c o m*/ HttpResponse httpResponse = httpClient.execute(request); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_CREATED) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(outputStream); String json = outputStream.toString(CharEncoding.UTF_8); throw new UnexpectedHttpStatusException(statusCode, "Failed to complete request. Status: " + httpResponse.getStatusLine() + '\n' + json); } return httpResponse; }
From source file:cc.sferalabs.libs.telegram.bot.api.TelegramBot.java
/** * Sends a request to the server./*w w w . j a v a 2 s .c o m*/ * * @param <T> * the class to cast the returned value to * @param request * the request to be sent * @param timeout * the read timeout value (in milliseconds) to be used for server * response. A timeout of zero is interpreted as an infinite * timeout * @return the JSON object representing the value of the field "result" of * the response JSON object cast to the specified type parameter * @throws ResponseError * if the server returned an error response, i.e. the value of * the field "ok" of the response JSON object is {@code false} * @throws ParseException * if an error occurs while parsing the server response * @throws IOException * if an I/O exception occurs */ @SuppressWarnings("unchecked") public <T> T sendRequest(Request request, int timeout) throws IOException, ParseException, ResponseError { HttpURLConnection connection = null; try { URL url = buildUrl(request); log.debug("Performing request: {}", url); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(timeout); if (request instanceof SendFileRequest) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Path filePath = ((SendFileRequest) request).getFilePath(); builder.addBinaryBody(((SendFileRequest) request).getFileParamName(), filePath.toFile()); HttpEntity multipart = builder.build(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", multipart.getContentType().getValue()); connection.setRequestProperty("Content-Length", "" + multipart.getContentLength()); try (OutputStream out = connection.getOutputStream()) { multipart.writeTo(out); } } else { connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Length", "0"); } boolean httpOk = connection.getResponseCode() == HttpURLConnection.HTTP_OK; try (InputStream in = httpOk ? connection.getInputStream() : connection.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { JSONObject resp = (JSONObject) parser.parse(br); log.debug("Response: {}", resp); boolean ok = (boolean) resp.get("ok"); if (!ok) { String description = (String) resp.get("description"); if (description == null) { description = "ok=false"; } throw new ResponseError(description); } return (T) resp.get("result"); } } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.aokyu.dev.pocket.PocketClient.java
private RequestToken retrieveRequestToken() throws IOException, InvalidRequestException, PocketException { String endpoint = PocketServer.getEndpoint(RequestType.OAUTH_REQUEST); URL requestUrl = new URL(endpoint); HttpHeaders headers = new HttpHeaders(); headers.put(HttpHeader.CONTENT_TYPE, ContentType.JSON_WITH_UTF8.get()); headers.put(HttpHeader.X_ACCEPT, ContentType.JSON.get()); headers.put(HttpHeader.HOST, requestUrl.getHost()); HttpParameters parameters = new HttpParameters(); parameters.put(AuthRequestParameter.CONSUMER_KEY, mConsumerKey.get()); parameters.put(AuthRequestParameter.REDIRECT_URI, PocketUtils.getRedirectUri(mConsumerKey)); HttpRequest request = new HttpRequest(HttpMethod.POST, requestUrl, headers, parameters); HttpResponse response = null;//from www . j av a 2 s . c om RequestToken requestToken = null; try { response = mClient.execute(request); if (response.getStatusCode() == HttpURLConnection.HTTP_OK) { JSONObject jsonObj = response.getResponseAsJSONObject(); requestToken = new RequestToken(jsonObj); } else { ErrorResponse error = new ErrorResponse(response); mErrorHandler.handleResponse(error); } } catch (JSONException e) { throw new PocketException(e.getMessage()); } finally { if (response != null) { response.disconnect(); } } return requestToken; }
From source file:com.bmc.gibraltar.automation.dataprovider.RestDataProvider.java
public boolean isUserExistent(String userLoginName) { int statusCode = userManagementApi.getUserInfo(userLoginName).extract().statusCode(); return statusCode == HttpURLConnection.HTTP_OK; }
From source file:net.sf.okapi.filters.drupal.DrupalConnector.java
public boolean postNode(Node node) { try {/*w ww. j a v a 2s . c om*/ URL url = new URL(host + String.format("rest/node")); HttpURLConnection conn = createConnection(url, "POST", true); OutputStream os = conn.getOutputStream(); os.write(node.toString().getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println(conn.getResponseCode()); System.out.println(conn.getResponseMessage()); throw new RuntimeException("Operation failed: " + conn.getResponseCode()); } conn.disconnect(); return true; } catch (Throwable e) { throw new RuntimeException("Error in postNode(): " + e.getMessage(), e); } }
From source file:com.nofuturecorp.www.connector.Database.java
/** * Make a post request to the PHP URL for process request and get data in JSON format * @param json with data to send/* ww w. ja va 2s . c om*/ * @return JSON with data received * @throws IOException * @throws DatabaseException */ private String makePostRequest(String json) throws IOException, DatabaseException { if (json == null) { throw new NullPointerException("json cannot be null"); } if (!ignoreSecureProtocol && url.toUpperCase().startsWith("HTTPS")) { throw new SecureProtocolException( "URL Protocol is not valid. Please use HTTPS or set true ignore secure protocol"); } StringBuffer data = null; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(("isTransaction=" + isTransaction + "&data=" + json).getBytes()); os.flush(); os.close(); int response = con.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; data = new StringBuffer(); while ((line = reader.readLine()) != null) { data.append(line); } String js = data.substring(data.indexOf("{")); return js; } else { throw new DatabaseException("HTTP connection fails. Response code: " + response); } }
From source file:com.andrious.btc.data.jsonUtils.java
private static boolean handleResponse(int response, HttpURLConnection conn) { if (response == HttpURLConnection.HTTP_OK) { return true; }/*from ww w . j av a 2 s. c o m*/ if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM || response == HttpURLConnection.HTTP_SEE_OTHER) { String newURL = conn.getHeaderField("Location"); conn.disconnect(); try { // get redirect url from "location" header field and open a new connection again conn = urlConnect(newURL); return true; } catch (IOException ex) { throw new RuntimeException(ex); } } // Nothing to be done. Can't go any further. return false; }