本文整理汇总了Java中com.jcabi.http.Response类的典型用法代码示例。如果您正苦于以下问题:Java Response类的具体用法?Java Response怎么用?Java Response使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Response类属于com.jcabi.http包,在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: safe_stage_should_continue_to_run_if_an_exception_is_thrown
import com.jcabi.http.Response; //导入依赖的package包/类
@Test
public void safe_stage_should_continue_to_run_if_an_exception_is_thrown() throws Exception {
String message = "Failure!";
Exit.OnSignal exit = new Exit.OnSignal();
new Thread(() -> unchecked(() -> {
Stage stage = safeStage(r -> {throw new ActException(message);});
stage.start(exit);
})).start();
Response response = new JdkRequest("http://localhost:8080/").fetch();
assertEquals(500, response.status());
assertEquals("Internal Server Error", response.reason());
assertEquals(message, response.body());
exit.stop();
Thread.sleep(1000);
}
示例2: read
import com.jcabi.http.Response; //导入依赖的package包/类
@Override
@NotNull(message = "file content can't be NULL")
public String read(@NotNull(message = "file name can't be NULL")
final String file) throws IOException {
final Response response = this.request.fetch();
final String url = response
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.as(JsonResponse.class)
.json().readObject().getJsonObject("files")
.getJsonObject(file).getString("raw_url");
return response
.as(RestResponse.class)
.jump(URI.create(url))
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.body();
}
示例3: processed
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Return a response after real processing of the CSS.
* @param css The CSS stylesheet to check
* @return The response
* @throws IOException if fails
*/
private ValidationResponse processed(final String css) throws IOException {
final Request req = this.request(
AbstractBaseValidator.entity(
"file", DefaultCssValidator.filter(css), "text/css"
)
);
final Response response = DefaultCssValidator.correct(req.fetch());
return DefaultCssValidator.build(
response.as(XmlResponse.class)
.registerNs("env", "http://www.w3.org/2003/05/soap-envelope")
.registerNs("m", "http://www.w3.org/2005/07/css-validator")
.assertXPath("//m:validity")
.assertXPath("//m:checkedby")
.xml()
);
}
示例4: correct
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Check if response from W3C contains some bad status.
* @param response Response from W3c.
* @return Response passed as parameter.
* @throws IOException when has some bad status.
*/
private static Response correct(final Response response)
throws IOException {
final List<Integer> statuses = Arrays.asList(
HttpURLConnection.HTTP_INTERNAL_ERROR,
HttpURLConnection.HTTP_NOT_IMPLEMENTED,
HttpURLConnection.HTTP_BAD_GATEWAY,
HttpURLConnection.HTTP_UNAVAILABLE,
HttpURLConnection.HTTP_GATEWAY_TIMEOUT,
HttpURLConnection.HTTP_VERSION
);
if (statuses.contains(response.status())) {
throw new IOException(
String.format(
"Bad status from W3C server: %1d",
response.status()
)
);
}
return response;
}
示例5: validate
import com.jcabi.http.Response; //导入依赖的package包/类
@Override
public ValidationResponse validate(final String html)
throws IOException {
final Request req = this.request(html);
final Response response = req.fetch();
if (response.status() != HttpURLConnection.HTTP_OK) {
throw new IOException(
response.reason()
);
}
return this.build(
response.as(XmlResponse.class)
.registerNs("nu", "http://n.validator.nu/messages/")
.assertXPath("//nu:messages")
.assertXPath("//nu:source")
.xml()
);
}
示例6: canListUsers
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Verifica si es el sistema está listando usuarios correctamente.
*
* @throws IOException
* Si no puede realizar la petición
*/
@Test
public void canListUsers() throws IOException {
/* Se realiza la petición al servicio. */
Request request = new JdkRequest(buildUrl("/users"))
.method(JdkRequest.GET);
Response response = request.fetch();
/*
* Se validan diferentes propiedades de la respuesta dada por el
* servicio.
*/
Assert.assertNotNull("El response es nulo", response);
Assert.assertNotNull("El cuerpo del response es nulo", response.body());
Assert.assertTrue("El cuerpo del mensaje está vacio", response.body()
.length() > 0);
Assert.assertEquals("El código de status no es 200", 200,
response.status());
Assert.assertTrue("El contenido no es correcto", response.body()
.contains("Juan"));
}
示例7: canGetEspecificUserError
import com.jcabi.http.Response; //导入依赖的package包/类
/**
*
* Verifica que el servicio responda de manera correcta al pedir un usuario
* que no existe
*
* @throws IOException
* Si no puede realizar la petición
*/
@Test
public void canGetEspecificUserError() throws IOException {
/* Se realiza la petición */
Request request = new JdkRequest(buildUrl("/users/30"))
.method(JdkRequest.GET);
Response response = request.fetch();
/* se verifican propiedades de la respuesta */
Assert.assertNotNull("El response es nulo", response);
Assert.assertNotNull("El cuerpo del mensaje es nulo", response.body());
Assert.assertEquals("El código de estatus es incorrecto", 404,
response.status());
/* se verifican las propiedades del mensaje que se respondió */
Gson gson = new Gson();
JsonObject data = gson.fromJson(response.body(), JsonObject.class);
Assert.assertEquals("El identificador del mensaje no es correcto",
HttpStatusCode._404.getId(), data.get("id").getAsString());
Assert.assertEquals("El mensaje de respuesta no es correcto",
HttpStatusCode._404.getMessage(), data.get("message")
.getAsString());
}
示例8: canDeleteUser
import com.jcabi.http.Response; //导入依赖的package包/类
/**
*
* Verifica la respuesta del servidor al tratar de eliminar un usuario.
*
* @throws IOException
* Si la petición no se puede realizar
*
*/
@Test
public void canDeleteUser() throws IOException {
/* Se realiza la petición al servicio */
Request request = new JdkRequest(buildUrl("/users/3"))
.method(JdkRequest.DELETE);
Response response = request.fetch();
/* Verifica de datos generales del response */
Assert.assertNotNull("El response es nulo", response);
Assert.assertNotNull("El cuerpo del mensaje es nulo", response.body());
Assert.assertNotNull("El cuerpo del mensaje está vacio", response
.body().length() > 0);
Assert.assertEquals("El código de estatus no es el correcto", 200,
response.status());
/* Verifica la información de la respuesta */
Gson gson = new Gson();
User user = gson.fromJson(response.body(), User.class);
Assert.assertEquals("La propiedad name es incorrecta", "José",
user.getName());
Assert.assertEquals("La propiedad lastName es incorrecta", "Ortiz",
user.getLastName());
Assert.assertEquals("La propiedad document es incorrecta",
"1094627938", user.getDocument());
}
示例9: canDeleteNonExistentUser
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Verifica la respuesta del servicio al tratar de eliminar un usuario que
* no existe.
*
* @throws IOException
* Si no puede realizar la petición
*/
@Test
public void canDeleteNonExistentUser() throws IOException {
/* Se realiza la petición al servicio */
Request request = new JdkRequest(buildUrl("/users/40"))
.method(JdkRequest.DELETE);
Response response = request.fetch();
/* Verifica de datos generales del response */
Assert.assertNotNull("El response es nulo", response);
Assert.assertNotNull("El cuerpo del mensaje es nulo", response.body());
Assert.assertNotNull("El cuerpo del mensaje está vacio", response
.body().length() > 0);
Assert.assertEquals("El código de estatus no es el correcto", 404,
response.status());
/* se verifican las propiedades del mensaje que se respondió */
Gson gson = new Gson();
JsonObject data = gson.fromJson(response.body(), JsonObject.class);
Assert.assertEquals("El identificador del mensaje no es correcto",
HttpStatusCode._404.getId(), data.get("id").getAsString());
Assert.assertEquals("El mensaje de respuesta no es correcto",
HttpStatusCode._404.getMessage(), data.get("message")
.getAsString());
}
示例10: fetchResponse
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Fetch response from server.
* @param stream The content to send.
* @return The obtained response
* @throws IOException If an IO exception occurs.
*/
private Response fetchResponse(final InputStream stream)
throws IOException {
final long start = System.currentTimeMillis();
final Response response = this.wire.send(
this, this.home, this.mtd,
this.hdrs, stream, this.connect,
this.read
);
final URI uri = URI.create(this.home);
Logger.info(
this,
"#fetch(%s %s%s %s): [%d %s] in %[ms]s",
this.mtd,
uri.getHost(),
// @checkstyle AvoidInlineConditionalsCheck (1 line)
uri.getPort() > 0 ? String.format(":%d", uri.getPort()) : "",
uri.getPath(),
response.status(),
response.reason(),
System.currentTimeMillis() - start
);
return response;
}
示例11: send
import com.jcabi.http.Response; //导入依赖的package包/类
@Override
public Response send(final Request req, final String home,
final String method,
final Collection<Map.Entry<String, String>> headers,
final InputStream content,
final int connect,
final int read) throws IOException {
final CloseableHttpResponse response =
HttpClients.createSystem().execute(
this.httpRequest(
home, method, headers, content,
connect, read
)
);
try {
return new DefaultResponse(
req,
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(),
this.headers(response.getAllHeaders()),
this.consume(response.getEntity())
);
} finally {
response.close();
}
}
示例12: get
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Get and cache.
* @param label Label to use
* @param wire Original wire
* @param request The request
* @param home URI to fetch
* @param method HTTP method
* @param headers Headers
* @param input Input body
* @param connect Connect timeout
* @param read Read timeout
* @return Response
* @throws IOException If fails
* @checkstyle ParameterNumberCheck (10 lines)
*/
public Response get(final String label, final Wire wire,
final Request request, final String home, final String method,
final Collection<Map.Entry<String, String>> headers,
final InputStream input, final int connect, final int read)
throws IOException {
final File file = this.file(label);
final Response rsp;
if (file.exists()) {
rsp = this.response(request, file);
} else {
rsp = this.saved(
wire.send(
request, home, method,
headers, input, connect, read
),
file
);
}
return rsp;
}
示例13: response
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Get response from file.
* @param req Request
* @param file File to read
* @return Response
* @throws IOException If fails
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private Response response(final Request req, final File file)
throws IOException {
final JsonObject json = Json.createReader(
new ByteArrayInputStream(
FileUtils.readFileToByteArray(file)
)
).readObject();
final List<Map.Entry<String, String>> map = new LinkedList<>();
final JsonObject headers = json.getJsonObject("headers");
for (final String name : headers.keySet()) {
for (final JsonString value
: headers.getJsonArray(name).getValuesAs(JsonString.class)) {
map.add(new AbstractMap.SimpleEntry<>(name, value.getString()));
}
}
Logger.debug(this, "cache loaded from %s", file);
return new DefaultResponse(
req,
json.getInt("status"),
json.getString("reason"),
new Array<>(map),
json.getString("body").getBytes("UTF-8")
);
}
示例14: saved
import com.jcabi.http.Response; //导入依赖的package包/类
/**
* Save response to file.
* @param response Response to save
* @param file File to read
* @return Response
* @throws IOException If fails
*/
private Response saved(final Response response, final File file)
throws IOException {
final JsonObjectBuilder json = Json.createObjectBuilder();
json.add("status", response.status());
json.add("reason", response.reason());
final JsonObjectBuilder headers = Json.createObjectBuilder();
for (final Map.Entry<String, List<String>> pair
: response.headers().entrySet()) {
final JsonArrayBuilder array = Json.createArrayBuilder();
for (final String value : pair.getValue()) {
array.add(value);
}
headers.add(pair.getKey(), array);
}
json.add("headers", headers);
json.add("body", response.body());
if (file.getParentFile().mkdirs()) {
Logger.debug(this, "directory created for %s", file);
}
try (final OutputStream out = new FileOutputStream(file)) {
Json.createWriter(out).write(json.build());
}
Logger.debug(this, "cache saved into %s", file);
return response;
}
示例15: send
import com.jcabi.http.Response; //导入依赖的package包/类
@Override
public Response send(final Request req, final String home,
final String method,
final Collection<Map.Entry<String, String>> headers,
final InputStream content,
final int connect, final int read) throws IOException {
synchronized (TrustedWire.class) {
final SSLSocketFactory def =
HttpsURLConnection.getDefaultSSLSocketFactory();
try {
HttpsURLConnection.setDefaultSSLSocketFactory(
TrustedWire.context().getSocketFactory()
);
return this.origin.send(
req, home, method, headers, content,
connect, read
);
} finally {
HttpsURLConnection.setDefaultSSLSocketFactory(def);
}
}
}