• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java Response类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.jcabi.http.Response的典型用法代码示例。如果您正苦于以下问题:Java Response类的具体用法?Java Response怎么用?Java Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Response类属于com.jcabi.http包,在下文中一共展示了Response类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
 
开发者ID:aliceice,项目名称:act,代码行数:19,代码来源:StageTest.java


示例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();
}
 
开发者ID:cvrebert,项目名称:typed-github,代码行数:20,代码来源:RtGist.java


示例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()
    );
}
 
开发者ID:jcabi,项目名称:jcabi-w3c,代码行数:23,代码来源:DefaultCssValidator.java


示例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;
}
 
开发者ID:jcabi,项目名称:jcabi-w3c,代码行数:27,代码来源:DefaultCssValidator.java


示例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()
    );
}
 
开发者ID:jcabi,项目名称:jcabi-w3c,代码行数:19,代码来源:DefaultHtmlValidator.java


示例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"));
}
 
开发者ID:juanprq,项目名称:spark-simple-api,代码行数:27,代码来源:AppTest.java


示例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());
}
 
开发者ID:juanprq,项目名称:spark-simple-api,代码行数:31,代码来源:AppTest.java


示例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());
}
 
开发者ID:juanprq,项目名称:spark-simple-api,代码行数:34,代码来源:AppTest.java


示例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());
}
 
开发者ID:juanprq,项目名称:spark-simple-api,代码行数:32,代码来源:AppTest.java


示例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;
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:30,代码来源:BaseRequest.java


示例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();
    }
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:27,代码来源:ApacheRequest.java


示例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;
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:36,代码来源:FcCache.java


示例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")
    );
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:33,代码来源:FcCache.java


示例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;
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:33,代码来源:FcCache.java


示例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);
        }
    }
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:23,代码来源:TrustedWire.java


示例16: send

import com.jcabi.http.Response; //导入依赖的package包/类
@Override
public final 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 Response rsp;
    if (method.equals(Request.GET) && !this.requestHasCmcHeader(headers)) {
        rsp = this.consultCache(
            req, home, method, headers, content, connect, read
        );
    } else {
        rsp = this.origin.send(
            req, home, method, headers, content, connect, read
        );
    }
    return rsp;
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:19,代码来源:AbstractHeaderBasedCachingWire.java


示例17: consultCache

import com.jcabi.http.Response; //导入依赖的package包/类
/**
 * Check cache and update if needed.
 *
 * @param req Request
 * @param home URI to fetch
 * @param method HTTP method
 * @param headers Headers
 * @param content HTTP body
 * @param connect The connect timeout
 * @param read The read timeout
 * @return Response obtained
 * @throws IOException if fails
 * @checkstyle ParameterNumber (6 lines)
 */
private Response consultCache(
    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 Response rsp;
    if (this.cache.containsKey(req)) {
        rsp = this.validateCacheWithServer(
            req, home, method, headers, content, connect, read
        );
    } else {
        rsp = this.origin.send(
            req, home, method, headers, content, connect, read
        );
        this.updateCache(req, rsp);
    }
    return rsp;
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:33,代码来源:AbstractHeaderBasedCachingWire.java


示例18: validateCacheWithServer

import com.jcabi.http.Response; //导入依赖的package包/类
/**
 * Check response and update cache or evict from cache if needed.
 * @param req Request
 * @param home URI to fetch
 * @param method HTTP method
 * @param headers Headers
 * @param content HTTP body
 * @param connect The connect timeout
 * @param read The read timeout
 * @return Response obtained
 * @throws IOException if fails
 * @checkstyle ParameterNumber (8 lines)
 */
private Response validateCacheWithServer(
    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 Response cached = this.cache.get(req);
    final Collection<Map.Entry<String, String>> hdrs = this.enrich(
        headers, cached
    );
    Response result = this.origin.send(
        req, home, method, hdrs, content, connect, read
    );
    if (result.status() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        result = cached;
    } else {
        this.updateCache(req, result);
    }
    return result;
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:33,代码来源:AbstractHeaderBasedCachingWire.java


示例19: enrich

import com.jcabi.http.Response; //导入依赖的package包/类
/**
 * Add identify content version header.
 *
 * @param headers Original headers
 * @param rsp Cached response
 * @return Map with extra header
 */
private Collection<Map.Entry<String, String>> enrich(
    final Collection<Map.Entry<String, String>> headers, final Response rsp
) {
    final Collection<String> list = rsp.headers().get(
        this.scvh
    );
    final Map<String, String> map =
        new ConcurrentHashMap<>(headers.size() + 1);
    for (final Map.Entry<String, String> entry : headers) {
        map.put(entry.getKey(), entry.getValue());
    }
    map.put(
        this.cmch, list.iterator().next()
    );
    return map.entrySet();
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:24,代码来源:AbstractHeaderBasedCachingWire.java


示例20: readsJsonDocument

import com.jcabi.http.Response; //导入依赖的package包/类
/**
 * JsonResponse can read and return a JSON document.
 * @throws Exception If something goes wrong inside
 */
@Test
public void readsJsonDocument() throws Exception {
    final Response resp = new FakeRequest()
        .withBody("{\n\t\r\"foo-foo\":2,\n\"bar\":\"\u20ac\"}")
        .fetch();
    final JsonResponse response = new JsonResponse(resp);
    MatcherAssert.assertThat(
        response.json().readObject().getInt("foo-foo"),
        Matchers.equalTo(2)
    );
    MatcherAssert.assertThat(
        response.json().readObject().getString("bar"),
        Matchers.equalTo("\u20ac")
    );
}
 
开发者ID:jcabi,项目名称:jcabi-http,代码行数:20,代码来源:JsonResponseTest.java



注:本文中的com.jcabi.http.Response类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java VersionMessage类代码示例发布时间:2022-05-22
下一篇:
Java IndexFileNames类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap