org.apache.http.HttpStatus#SC_OK源码实例Demo

下面列出了org.apache.http.HttpStatus#SC_OK 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: arcusplatform   文件: HomeGraphAPI.java
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();
      }
   }
}
 
源代码2 项目: gerrit-code-review-plugin   文件: Checks.java
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);
  }
}
 
源代码3 项目: teammates   文件: JoinCourseAction.java
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);
}
 
源代码4 项目: esigate   文件: DriverTest.java
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());
}
 
源代码5 项目: servicecomb-java-chassis   文件: KieClient.java
/**
 * 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;
}
 
源代码6 项目: xmfcn-spring-cloud   文件: HttpClientUtil.java
/**
 * 发送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;
}
 
源代码7 项目: davmail   文件: ExchangeDavRequest.java
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);
            }
        }
    }

}
 
源代码8 项目: dubbox   文件: RestExpressInvoker.java
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;
}
 
@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;

}
 
源代码10 项目: mvn-golang   文件: AbstractGolangMojo.java
@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();
  }
}
 
源代码11 项目: teammates   文件: DatastoreBackupAction.java
@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());
    }
}
 
源代码12 项目: pentaho-reporting   文件: JCRSolutionFileModel.java
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
  }
}
 
源代码13 项目: docker-java-api   文件: RtExecsTestCase.java
/**
 * 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()
        )
    );
}
 
源代码14 项目: carbon-apimgt   文件: HttpRequestUtil.java
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;
}
 
源代码15 项目: pacbot   文件: HttpUtil.java
/**
 * 
 * @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;
	}
}
 
源代码16 项目: skywalking   文件: ElasticSearch7Client.java
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;
}
 
源代码17 项目: product-emm   文件: MockHttpClient.java
public void setResponseData(HttpEntity entity) {
    mStatusCode = HttpStatus.SC_OK;
    mResponseEntity = entity;
}
 
private Boolean isSuccess(int statusCode) {
    return statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
}
 
private boolean createdSuccessfully(Response connectorResponse) {
    return connectorResponse.getStatus() == HttpStatus.SC_CREATED || connectorResponse.getStatus() == HttpStatus.SC_OK;
}
 
源代码20 项目: android-project-wo2b   文件: NetworkResponse.java
public NetworkResponse(byte[] data) {
    this(HttpStatus.SC_OK, data, Collections.<String, String>emptyMap(), false);
}