本文整理匯總了Java中io.vertx.core.http.HttpServerResponse類的典型用法代碼示例。如果您正苦於以下問題:Java HttpServerResponse類的具體用法?Java HttpServerResponse怎麽用?Java HttpServerResponse使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpServerResponse類屬於io.vertx.core.http包,在下文中一共展示了HttpServerResponse類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: sendFile
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) {
HttpServerResponse response = routingContext.response();
response.putHeader("Content-Description", "File Transfer");
response.putHeader("Content-Type", "application/octet-stream");
response.putHeader("Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name?
response.putHeader("Content-Transfer-Encoding", "binary");
response.putHeader("Expires", "0");
response.putHeader("Pragma", "Public");
response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.putHeader("Content-Length", "" + saneFile.length());
response.sendFile(saneFile.getAbsolutePath());
}
示例2: addResponseHeaders
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
default void addResponseHeaders(RouteDefinition definition, HttpServerResponse response) {
if (!response.ended() &&
!response.headers().contains(HttpHeaders.CONTENT_TYPE)) {
if (definition != null &&
definition.getProduces() != null) {
for (MediaType produces : definition.getProduces()) {
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaTypeHelper.toString(produces));
}
}
else {
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD);
}
}
}
示例3: getFormattedElement
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
@Test
public void getFormattedElement() {
AccessLogParam param = new AccessLogParam();
RoutingContext mockContext = Mockito.mock(RoutingContext.class);
HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
VertxHttpHeaders headers = new VertxHttpHeaders();
String headerValue = "headerValue";
param.setRoutingContext(mockContext);
headers.add(IDENTIFIER, headerValue);
Mockito.when(mockContext.response()).thenReturn(mockResponse);
Mockito.when(mockResponse.headers()).thenReturn(headers);
String result = ELEMENT.getFormattedElement(param);
assertEquals(headerValue, result);
assertEquals(ELEMENT.getIdentifier(), IDENTIFIER);
}
示例4: getFormattedElementOnNotFound
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
@Test
public void getFormattedElementOnNotFound() {
AccessLogParam param = new AccessLogParam();
RoutingContext mockContext = Mockito.mock(RoutingContext.class);
HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
VertxHttpHeaders headers = new VertxHttpHeaders();
String headerValue = "headerValue";
param.setRoutingContext(mockContext);
headers.add("anotherHeader", headerValue);
Mockito.when(mockContext.response()).thenReturn(mockResponse);
Mockito.when(mockResponse.headers()).thenReturn(headers);
String result = ELEMENT.getFormattedElement(param);
assertEquals("-", result);
}
示例5: handle
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
public void handle(RoutingContext ctx) {
HttpServerResponse response = ctx.response();
if (userManager.isLogined(ctx)) {
try {
String uid = userManager.getUid(userManager.getIdFromSession(ctx));
JobResult result = requestManager.getApiKeys(uid);
if (result.isSuccess()) {
SafeResultSet rs = (SafeResultSet) result.getArgs()[0];
while (rs.next()) {
//
//
//
}
}
} catch (SQLException e) {
e.printStackTrace();
response.setStatusCode(500);
}
} else {
response.setStatusCode(400);
}
response.end();
response.close();
}
示例6: writeDatasetContents
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
private void writeDatasetContents(
RoutingContext routingContext, Observable<DataEnvelope> datasetContents) {
HttpServerResponse httpServerResponse =
jsonContentType(routingContext.response()).setChunked(true);
final AtomicBoolean isFirst = new AtomicBoolean(true);
datasetContents.subscribe(
(DataEnvelope dataEnvelope) -> {
if (!isFirst.get()) {
httpServerResponse.write(",");
} else {
isFirst.set(false);
httpServerResponse.write("[");
}
httpServerResponse.write(new JsonObject(dataEnvelope.getPayload()).encodePrettily());
},
throwable -> GlobalExceptionHandler.error(routingContext, throwable),
() -> httpServerResponse.end("]"));
}
示例7: writeDatasets
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
private void writeDatasets(RoutingContext routingContext, Observable<Dataset> datasets) {
HttpServerResponse httpServerResponse =
jsonContentType(routingContext.response()).setChunked(true);
final AtomicBoolean isFirst = new AtomicBoolean(true);
datasets.subscribe(
dataset -> {
if (!isFirst.get()) {
httpServerResponse.write(",");
} else {
isFirst.set(false);
httpServerResponse.write("[");
}
httpServerResponse.write(viewTransformer.transform(dataset));
},
throwable -> GlobalExceptionHandler.error(routingContext, throwable),
() -> httpServerResponse.end("]"));
}
示例8: applyForOauth
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
/**
* 申請微信授權
* /awp/wxOauth/apply/{body}
* web服務需要授權時,向用戶發送重定向,重定向到當前接口
* 參數隻有一個,內容為JSON,請用http://localhost:8083/awp/base64.html進行加密
* {
* "eid":web項目使用的公眾號在本項目中的用戶ID
* "type":0=靜默授權,隻能獲取OpenID,1=正常授權,會彈出授權確認頁麵,可以獲取到用戶信息
* "callback":授權成功後調用的web項目回調接口地址,請使用完整地址,
* 回調時會使用GET方法,加上rs參數,
* 如果靜默授權,rs參數內容就是openid
* 如果正常授權,rs參數內容是turingBase64加密的授權結果(JSON)
* }
*
* @param rc Vertx的RoutingContext對象
* @author Leibniz.Hu
*/
private void applyForOauth(RoutingContext rc) {
HttpServerResponse resp = rc.response();
String decodedBody = TuringBase64Util.decode(rc.request().getParam("body"));
JsonObject reqJson = new JsonObject(decodedBody);
Integer eid = reqJson.getInteger("eid");
int type = reqJson.getInteger("type");
String callback = TuringBase64Util.encode(reqJson.getString("callback"));//授權後回調方法
vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
if (ar.succeeded()) {
JsonObject account = ar.result().body();
String redirectAfterUrl = PROJ_URL + "oauth/wx/" + (type == 0 ? "baseCb" : "infoCb") + "?eid=" + eid + "&visitUrl=" + callback;
String returnUrl = null;
try {
returnUrl = String.format((type == 0 ? OAUTH_BASE_API : OAUTH_INFO_API)
, account.getString(WXAPPID), URLEncoder.encode(redirectAfterUrl, "UTF-8"));
} catch (UnsupportedEncodingException ignored) { //不可能出現的
}
resp.setStatusCode(302).putHeader("Location", returnUrl).end();
} else {
log.error("EventBus消息響應錯誤", ar.cause());
resp.setStatusCode(500).end("EventBus error!");
}
});
}
示例9: applyForOauth
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
/**
* 申請支付寶授權
* /awp/wxOauth/apply/{body}
* web服務需要授權時,向用戶發送重定向,重定向到當前接口
* 參數隻有一個,內容為JSON,請用http://localhost:8083/awp/base64.html進行加密
* {
* "eid":web項目使用的公眾號在本項目中的用戶ID
* "type":0=靜默授權,隻能獲取OpenID,1=正常授權,會彈出授權確認頁麵,可以獲取到用戶信息
* "callback":授權成功後調用的web項目回調接口地址,請使用完整地址,
* 回調時會使用GET方法,加上rs參數,
* 如果靜默授權,rs參數內容就是openid
* 如果正常授權,rs參數內容是turingBase64加密的授權結果(JSON)
* }
*
* @param rc Vertx的RoutingContext對象
* @author Leibniz.Hu
*/
private void applyForOauth(RoutingContext rc) {
HttpServerResponse resp = rc.response();
String decodedBody = TuringBase64Util.decode(rc.request().getParam("body"));
JsonObject reqJson = new JsonObject(decodedBody);
Integer eid = reqJson.getInteger("eid");
int type = reqJson.getInteger("type");
String callback = TuringBase64Util.encode(reqJson.getString("callback"));//授權後回調方法
vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
if (ar.succeeded()) {
JsonObject acc = ar.result().body();
String redirectAfterUrl = PROJ_URL + "oauth/zfb/" + (type == 0 ? "baseCb" : "infoCb") + "?eid=" + eid + "&visitUrl=" + callback;
AliAccountInfo aliAcc = new AliAccountInfo(acc.getString(ZFBAPPID), acc.getString(ZFBPRIVKEY), acc.getString(ZFBPUBKEY), null, null, redirectAfterUrl);
AliPayApi.auth(aliAcc, resp, type == 1);
} else {
log.error("EventBus消息響應錯誤", ar.cause());
resp.setStatusCode(500).end("EventBus error!");
}
});
}
示例10: updateAlipayPaySetting
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
private void updateAlipayPaySetting(RoutingContext rc) {
if (forbidAccess(rc, "uid", true)) {
return;
}
HttpServerRequest req = rc.request();
HttpServerResponse resp = rc.response().putHeader("content-type", "application/json; charset=utf-8");
//解析參數
Long uid = Long.parseLong(req.getParam("uid"));
Integer paySwitch = Integer.parseInt(req.getParam("paySwitch"));
String appId = req.getParam("appId");
String appPrivKey = req.getParam("appPrivKey");
String zfbPubKey = req.getParam("zfbPubKey");
//參數檢查
if (paySwitch == 1 && !CommonUtils.notEmptyString(appId, appPrivKey, zfbPubKey)) {
resp.end(new JsonObject().put("status", "invalid").toString());
return;
}
//保存支付參數
JsonObject acc = new JsonObject().put(ID, uid).put(ZFBAPPID, appId).put(ZFBPRIVKEY, appPrivKey).put(ZFBPUBKEY, zfbPubKey).put(ZFBPAYON, paySwitch);
updatePaySetting(resp, acc, COMMAND_UPDATE_ALIPAY);
}
示例11: refuseNonLanAccess
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
/**
* 判斷當前請求是否允許,如果不允許,則將狀態碼設為403並結束響應
*
* @return true:禁止訪問 false=允許訪問
* @author Leibniz.Hu
*/
protected boolean refuseNonLanAccess(RoutingContext rc) {
HttpServerRequest req = rc.request();
HttpServerResponse resp = rc.response();
String realIp = req.getHeader("X-Real-IP");
String xforward = req.getHeader("X-Forwarded-For");
//禁止外網訪問
if (realIp != null && !isLanIP(realIp)) {
log.warn("檢測到非法訪問,來自X-Real-IP={}", realIp);
resp.setStatusCode(403).end();
return true;
}
if (xforward != null && !isLanIP(xforward)) {
log.warn("檢測到非法訪問,來自X-Forwarded-For={}", xforward);
resp.setStatusCode(403).end();
return true;
}
return false;
}
示例12: wapPay
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
/**
* 該方法實現了支付寶手機網頁的支付功能;
* 方法將調用支付寶支付頁麵需要用到的數據拚接和設置好,然後,寫到響應中,前台會自動彈出支付寶支付頁麵;
* 其中,支付金額要求大於0.01,並且小於100000000,需要調用者自己檢查該值再傳進來,否則頁麵會報獲取不到訂單信息錯誤;
*
* @param aliAccountInfo 保存了支付寶賬戶的信息,包括appId、用戶私鑰、支付寶公鑰和回調地址等,具體參考AliAccountInfo類的屬性說明
* @param payBizContent 保存了訂單信息,包括本地訂單號、金額等,具體參考BizContent類的屬性說明
* Create by quandong
*/
public static void wapPay(AliAccountInfo aliAccountInfo, PayBizContent payBizContent, HttpServerResponse httpResponse) throws IOException {
AlipayClient alipayClient = AliPayCliFactory.getAlipayClient(aliAccountInfo); // 從客戶端工廠中獲取AlipayClient
AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); // 創建API對應的request
String form = "";
alipayRequest.setReturnUrl(aliAccountInfo.getReturnUrl()); // 設置回跳地址
alipayRequest.setNotifyUrl(aliAccountInfo.getNotifyUrl()); // 設置通知地址
alipayRequest.setBizContent(payBizContent.toString()); // 填充業務參數
try {
form = alipayClient.pageExecute(alipayRequest).getBody(); // 調用SDK生成表單
} catch (AlipayApiException e) {
e.printStackTrace();
}
httpResponse.putHeader("Content-Type", "text/html;charset=" + AlipayConstants.CHARSET_UTF8); // 設置文本類型及編碼
httpResponse.end(form); // 直接將完整的表單html輸出到頁麵
}
示例13: wechatPreHandle
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
/**
* 微信支付的預處理,js的wx.config需要用
*
* 異步返回 wx.config需要用的數據
*
* @author Leibniz
*/
private void wechatPreHandle(RoutingContext rc) {
HttpServerRequest req = rc.request();
HttpServerResponse response = rc.response();
int eid = Integer.parseInt(req.getParam("eid"));
vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
if (ar.succeeded()) {
JsonObject acc = ar.result().body();
String curUrl = null;
try {
curUrl = URLDecoder.decode(req.getParam("url"), "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
//調用微信jdk類
Map<String, String> jdkMap = new WechatJdk(req, acc, curUrl).getMap();
jdkMap.put("appId", acc.getString(WXAPPID));
String jsonStr = JsonObject.mapFrom(jdkMap).toString();
log.debug("接收到(ID={})微信JSSDK初始化請求,返回Json:{}", eid, jsonStr);
response.putHeader("content-type", "application/json;charset=UTF-8").end(jsonStr);
} else {
log.error("EventBus消息響應錯誤", ar.cause());
response.setStatusCode(500).end("EventBus error!");
}
});
}
示例14: handle
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
@Override
public void handle(RoutingContext routingContext) {
String id = routingContext.request().getParam(MESSAGE_ID);
redisClient.hget(MESSAGES, id, result -> {
HttpServerResponse response = routingContext.response();
if (result == null) {
response.setStatusCode(404);
response.end();
} else {
response.setStatusCode(200);
response.putHeader("content-type", "application/json; charset=utf-8");
response.end(result.result());
}
});
}
示例15: reply
import io.vertx.core.http.HttpServerResponse; //導入依賴的package包/類
public static void reply(
final RoutingContext context,
final Envelop envelop,
final Event event
) {
// 1. Get response reference
final HttpServerResponse response
= context.response();
// 2. Set response status
final HttpStatusCode code = envelop.status();
response.setStatusCode(code.code());
response.setStatusMessage(code.message());
// 3. Media processing
Normalizer.out(response, envelop, event);
// 4. Store Session
storeSession(context, envelop.data(), event.getAction());
// 5. Response process
if (!response.ended()) {
response.end(envelop.response());
}
response.close();
}