Java Code Examples for org.apache.http.HttpStatus#SC_OK

The following examples show how to use org.apache.http.HttpStatus#SC_OK . 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 File: Checks.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public CheckInfo get(String checkerUuid) throws RestApiException {
  try {
    HttpGet request = new HttpGet(buildRequestUrl(checkerUuid));
    try (CloseableHttpResponse response = client.execute(request)) {
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return JsonBodyParser.parseResponse(
            EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
      }
      throw new RestApiException(
          String.format(
              "Request failed with status: %d", response.getStatusLine().getStatusCode()));
    }
  } catch (Exception e) {
    throw new RestApiException("Failed to get check info: ", e);
  }
}
 
Example 2
Source File: ExchangeDavRequest.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected void handlePropstat(XMLStreamReader reader, MultiStatusResponse multiStatusResponse) throws XMLStreamException {
    int propstatStatus = 0;
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, "propstat")) {
        reader.next();
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagLocalName = reader.getLocalName();
            if ("status".equals(tagLocalName)) {
                if ("HTTP/1.1 200 OK".equals(reader.getElementText())) {
                    propstatStatus = HttpStatus.SC_OK;
                } else {
                    propstatStatus = 0;
                }
            } else if ("prop".equals(tagLocalName) && propstatStatus == HttpStatus.SC_OK) {
                handleProperty(reader, multiStatusResponse);
            }
        }
    }

}
 
Example 3
Source File: HttpClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 发送get请求
 *
 * @param url 路径
 * @return
 */
public static JSONObject httpGet(String url) {
    // get请求返回结果
    JSONObject jsonResult = null;
    try {
        HttpClient client = HttpClientBuilder.create().build();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.addHeader("", "");
        HttpResponse response = client.execute(request);

        /** 请求发送成功,并得到响应 **/
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            /** 读取服务器返回过来的json字符串数据 **/
            String strResult = EntityUtils.toString(response.getEntity());
            /** 把json字符串转换成json对象 **/
            jsonResult = JSONObject.parseObject(strResult);
            url = URLDecoder.decode(url, "UTF-8");
        } else {
            logger.error("get请求提交失败:" + url);
        }
    } catch (IOException e) {
        logger.error("get请求提交失败:" + url, e);
    }
    return jsonResult;
}
 
Example 4
Source File: KieClient.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Create value of a key
 *
 * @param key
 * @param kvBody
 * @return key-value json string; when some error happens, return null
 */
public String putKeyValue(String key, KVBody kvBody) {
  try {
    ObjectMapper mapper = new ObjectMapper();
    HttpResponse response = httpClient.putHttpRequest("/kie/kv/" + key, null, mapper.writeValueAsString(kvBody));
    if (response.getStatusCode() == HttpStatus.SC_OK) {
      return response.getContent();
    } else {
      LOGGER.error("create keyValue fails, responseStatusCode={}, responseMessage={}, responseContent{}",
          response.getStatusCode(), response.getMessage(), response.getContent());
    }
  } catch (IOException e) {
    LOGGER.error("create keyValue fails", e);
  }
  return null;
}
 
Example 5
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testForwardCookiesWithPortsAndPreserveHost() throws Exception {
    // Conf
    Properties properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080/") //
            .set(Parameters.PRESERVE_HOST, true) //
            .build();

    mockConnectionManager = new MockConnectionManager() {
        @Override
        public HttpResponse execute(HttpRequest httpRequest) {
            Assert.assertNotNull("Cookie should be forwarded", httpRequest.getFirstHeader("Cookie"));
            Assert.assertEquals("JSESSIONID=926E1C6A52804A625DFB0139962D4E13", httpRequest.getFirstHeader("Cookie")
                    .getValue());
            return new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
        }
    };

    Driver driver = createMockDriver(properties, mockConnectionManager);

    BasicClientCookie cookie = new BasicClientCookie("_JSESSIONID", "926E1C6A52804A625DFB0139962D4E13");
    request = TestUtils.createIncomingRequest("http://127.0.0.1:8081/foobar.jsp").addCookie(cookie);

    driver.proxy("/foobar.jsp", request.build());
}
 
Example 6
Source File: JoinCourseAction.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
private JsonResult joinCourseForInstructor(String regkey, String institute, String mac) {
    InstructorAttributes instructor;

    try {
        instructor = logic.joinCourseForInstructor(regkey, userInfo.id, institute, mac);
    } catch (EntityDoesNotExistException ednee) {
        return new JsonResult(ednee.getMessage(), HttpStatus.SC_NOT_FOUND);
    } catch (EntityAlreadyExistsException eaee) {
        return new JsonResult(eaee.getMessage(), HttpStatus.SC_BAD_REQUEST);
    } catch (InvalidParametersException ipe) {
        return new JsonResult(ipe.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    sendJoinEmail(instructor.courseId, instructor.name, instructor.email, true);

    return new JsonResult("Instructor successfully joined course", HttpStatus.SC_OK);
}
 
Example 7
Source File: HomeGraphAPI.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void requestSync(String accessToken) {
   if(accessToken == null) {
      return;
   }

   try(Timer.Context ctxt = GoogleMetrics.startRequestSyncTimer()) {
      Map<String, String> body = ImmutableMap.of(PROP_USERAGENT, accessToken);
      String bodyStr = JSON.toJson(body);
      HttpPost post = createPost(createUrl(REQUEST_SYNC), ContentType.APPLICATION_JSON, new StringEntity(bodyStr, StandardCharsets.UTF_8));
      try(CloseableHttpClient client = httpClient()) {
         HttpEntity entity = null;
         try(CloseableHttpResponse response = client.execute(post)) {
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
               logger.warn("failed to issue requestSync for {}: {}", accessToken, response.getStatusLine().getStatusCode());
               entity = response.getEntity();
               GoogleMetrics.incRequestSyncFailures();
            }
         } finally {
            consumeQuietly(entity);
         }
      } catch(Exception e) {
         logger.warn("failed to issue requestSync for {}", accessToken, e);
         GoogleMetrics.incRequestSyncFailures();
      }
   }
}
 
Example 8
Source File: AbstractGolangMojo.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
@Nonnull
private String loadGoLangSdkList(@Nullable final ProxySettings proxySettings, @Nullable final String keyPrefix) throws IOException, MojoExecutionException {
  final String sdksite = getSdkSite() + (keyPrefix == null ? "" : "?prefix=" + keyPrefix);

  getLog().warn("Loading list of available GoLang SDKs from " + sdksite);
  final HttpGet get = new HttpGet(sdksite);

  final RequestConfig config = processRequestConfig(proxySettings, this.getConnectionTimeout(), RequestConfig.custom()).build();
  get.setConfig(config);

  get.addHeader("Accept", "application/xml");

  try {
    final HttpResponse response = getHttpClient(proxySettings).execute(get);
    final StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      final String content = EntityUtils.toString(response.getEntity());
      getLog().info("GoLang SDK list has been loaded successfuly");
      getLog().debug(content);
      return content;
    } else {
      throw new IOException(String.format("Can't load list of SDKs from %s : %d %s", sdksite, statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }
  } finally {
    get.releaseConnection();
  }
}
 
Example 9
Source File: DatastoreBackupAction.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void execute() {
    if (Config.isDevServer()) {
        log.info("Skipping backup in dev server.");
        return;
    }
    if (!Config.ENABLE_DATASTORE_BACKUP) {
        log.info("Skipping backup by system admin's choice.");
        return;
    }
    List<String> scopes = new ArrayList<>();
    scopes.add("https://www.googleapis.com/auth/datastore");
    String accessToken = AppIdentityServiceFactory.getAppIdentityService().getAccessToken(scopes).getAccessToken();
    String appId = Config.APP_ID;

    HttpPost post = new HttpPost("https://datastore.googleapis.com/v1/projects/" + appId + ":export");
    post.setHeader("Content-Type", "application/json");
    post.setHeader("Authorization", "Bearer " + accessToken);

    Map<String, Object> body = new HashMap<>();
    String timestamp = Instant.now().toString();
    // Documentation is wrong; the param name is output_url_prefix instead of outputUrlPrefix
    body.put("output_url_prefix", "gs://" + Config.BACKUP_GCS_BUCKETNAME + "/datastore-backups/" + timestamp);

    StringEntity entity = new StringEntity(JsonUtils.toJson(body), Charset.forName("UTF-8"));
    post.setEntity(entity);

    try (CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse resp = client.execute(post);
            BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()))) {
        String output = br.lines().collect(Collectors.joining(System.lineSeparator()));
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            log.info("Backup request successful:" + System.lineSeparator() + output);
        } else {
            log.severe("Backup request failure:" + System.lineSeparator() + output);
        }
    } catch (IOException e) {
        log.severe("Backup request failure: " + e.getMessage());
    }
}
 
Example 10
Source File: JCRSolutionFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void setData( final FileName file, final byte[] data ) throws FileSystemException {
  final String[] fileName = computeFileNames( file );
  final StringBuilder b = new StringBuilder();
  for ( int i = 0; i < fileName.length; i++ ) {
    if ( i != 0 ) {
      b.append( SLASH );
    }
    b.append( fileName[ i ] );
  }

  String service = MessageFormat.format( UPLOAD_SERVICE,
    URLEncoder.encodeUTF8( normalizePath( b.toString() ).replaceAll( "\\!", "%21" ).replaceAll( "\\+", "%2B" ) ) );
  final WebResource resource = client.resource( url + service );
  final ByteArrayInputStream stream = new ByteArrayInputStream( data );
  final ClientResponse response = resource.put( ClientResponse.class, stream );
  final int status = response.getStatus();

  if ( status != HttpStatus.SC_OK ) {
    if ( status == HttpStatus.SC_MOVED_TEMPORARILY
      || status == HttpStatus.SC_FORBIDDEN
      || status == HttpStatus.SC_UNAUTHORIZED ) {
      throw new FileSystemException( "ERROR_INVALID_USERNAME_OR_PASSWORD" );
    } else {
      throw new FileSystemException( "ERROR_FAILED", status );
    }
  }

  try {
    // Perhaps a New file was created. Refresh local tree model.
    this.refresh();
  } catch ( IOException e ) {
    // Ignore if unable to refresh
  }
}
 
Example 11
Source File: RtExecsTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * An Exec can return its JSON inspection.
 * @throws Exception If something goes wrong.
 */
@Test
public void execReturnsItsInspection() throws Exception {
    final Execs all = new RtExecs(
        new AssertRequest(
            new Response(
                HttpStatus.SC_OK,
                "{\"Id\": \"exec123\"}"
            ),
            new Condition(
                "inspect() must send a GET request",
                req -> "GET".equals(req.getRequestLine().getMethod())
            ),
            new Condition(
                "inspect() resource URL should end with '/exec123/json'",
                req -> req.getRequestLine()
                        .getUri().endsWith("/exec123/json")
            )
        ),
        URI.create("http://localhost/exec"),
        Mockito.mock(Docker.class)
    );
    final Exec exec = all.get("exec123");
    MatcherAssert.assertThat(exec, Matchers.notNullValue());
    MatcherAssert.assertThat(
        exec.inspect(),
        Matchers.equalTo(
            Json.createObjectBuilder()
                .add("Id", "exec123")
                .build()
        )
    );
}
 
Example 12
Source File: HttpRequestUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static String handleResponse(HttpResponse response, String methodName, boolean retry, int executionCount,
                                     int retryCount, String uri) throws OnPremiseGatewayException {
    switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            return handleSuccessCase(response);

        case HttpStatus.SC_CREATED:
            return handleSuccessCase(response);

        case HttpStatus.SC_ACCEPTED:
            return handleSuccessCase(response);

        case HttpStatus.SC_NOT_FOUND:
            throw new OnPremiseGatewayException(NOT_FOUND_ERROR_MSG);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new OnPremiseGatewayException(AUTH_ERROR_MSG);

        case HttpStatus.SC_FORBIDDEN:
            throw new OnPremiseGatewayException(AUTH_FORBIDDEN_ERROR_MSG);

        default:
            if (retry) {
                handleDefaultCaseWithRetry(executionCount, response, retryCount, methodName, uri);
            } else {
                throw new OnPremiseGatewayException(
                        methodName + " request failed for URI: " + uri + " with HTTP error code : " + response);
            }
    }
    return OnPremiseGatewayConstants.EMPTY_STRING;
}
 
Example 13
Source File: TwitterSharesButton.java    From android-socialbuttons with Apache License 2.0 5 votes vote down vote up
@Override
protected Long doInBackground(String... uri) {

	HttpClient httpclient = new DefaultHttpClient();
	HttpResponse response;
	Long shares = null;
	try {

		HttpGet getRequest = new HttpGet("http://urls.api.twitter.com/1/urls/count.json?url=" + URLEncoder.encode(uri[0], "UTF-8"));
		response = httpclient.execute(getRequest);
		StatusLine statusLine = response.getStatusLine();
		if(statusLine.getStatusCode() == HttpStatus.SC_OK){
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			response.getEntity().writeTo(out);
			out.close();
			JSONObject result = new JSONObject(out.toString());
			shares = result.getLong("count");
		} else{
			//Closes the connection.
			response.getEntity().getContent().close();
			throw new IOException(statusLine.getReasonPhrase());
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return shares;

}
 
Example 14
Source File: HttpUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error(requestBody);
			throw new Exception(
					"unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		parseException.printStackTrace();
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		exception.printStackTrace();
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
Example 15
Source File: RestExpressInvoker.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static byte[] post(String url, byte[] requestContent, Map<String, String> headerMap) throws IOException {
	HttpPost httpPost = new HttpPost(url);
	if (requestContent != null) {
		HttpEntity httpEntity = new ByteArrayEntity(requestContent);
		httpPost.setEntity(httpEntity);
	}
	if (headerMap != null) {
		for (Map.Entry<String, String> entry : headerMap.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}
	}
	HttpResponse response = httpclient.execute(httpPost);
	int responseCode = response.getStatusLine().getStatusCode();
	if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_CREATED
			|| responseCode == HttpStatus.SC_ACCEPTED || responseCode == HttpStatus.SC_NO_CONTENT) {
		HttpEntity responseEntity = response.getEntity();
		if (responseEntity != null) {
			return EntityUtils.toByteArray(responseEntity);
		}
	} else if (responseCode == HttpStatus.SC_NOT_FOUND) {
		throw new RpcException(RpcException.UNKNOWN_EXCEPTION, "not found service for url [" + url + "]");
	} else if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
		throw new RpcException(RpcException.NETWORK_EXCEPTION, "occur an exception at server end.");
	} else {
		throw new RpcException(RpcException.NETWORK_EXCEPTION, "Unknow HttpStatus Code");
	}
	return null;
}
 
Example 16
Source File: ElasticSearch7Client.java    From skywalking with Apache License 2.0 5 votes vote down vote up
public int delete(String indexName, String timeBucketColumnName, long endTimeBucket) throws IOException {
    indexName = formatIndexName(indexName);

    DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName);
    deleteByQueryRequest.setAbortOnVersionConflict(false);
    deleteByQueryRequest.setQuery(QueryBuilders.rangeQuery(timeBucketColumnName).lte(endTimeBucket));
    BulkByScrollResponse bulkByScrollResponse = client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
    log.debug(
        "delete indexName: {}, by query request: {}, response: {}", indexName, deleteByQueryRequest,
        bulkByScrollResponse
    );
    return HttpStatus.SC_OK;
}
 
Example 17
Source File: MockHttpClient.java    From product-emm with Apache License 2.0 4 votes vote down vote up
public void setResponseData(HttpEntity entity) {
    mStatusCode = HttpStatus.SC_OK;
    mResponseEntity = entity;
}
 
Example 18
Source File: EmailActionExecutor.java    From remote-monitoring-services-java with MIT License 4 votes vote down vote up
private Boolean isSuccess(int statusCode) {
    return statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
}
 
Example 19
Source File: CreateTelephonePaymentService.java    From pay-publicapi with MIT License 4 votes vote down vote up
private boolean createdSuccessfully(Response connectorResponse) {
    return connectorResponse.getStatus() == HttpStatus.SC_CREATED || connectorResponse.getStatus() == HttpStatus.SC_OK;
}
 
Example 20
Source File: NetworkResponse.java    From android-project-wo2b with Apache License 2.0 4 votes vote down vote up
public NetworkResponse(byte[] data) {
    this(HttpStatus.SC_OK, data, Collections.<String, String>emptyMap(), false);
}