将HttpServletRequest和HttpServletResponse临时存储为HttpServlet的两个字段(见下文)是一种好的做法/安全吗?如果没有,为什么?
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet
{
private HttpServletRequest req;
private HttpServletResponse resp;
@Override
protected void doPost(
HttpServletRequest req,
HttpServletResponse resp
)
throws ServletException, IOException
{
try
{
this.req=req;
this.resp=resp;
do1();
do2();
}
finally
{
this.req=null;
this.resp=null;
}
}
private void do1() throws ServletException, IOException
{
//use req resp
}
private void do2() throws ServletException, IOException
{
//use req resp
}
}
Run Code Online (Sandbox Code Playgroud)
或者我应该调用类似的东西:
do1(req,resp); …Run Code Online (Sandbox Code Playgroud) headers_list()并apache_reponse_headers()返回实际响应头的大大降低列表,即使在headers_sent()与get_headers()将使另一个HTTP请求.
那么,如何获得与当前页面一起发送的响应头的完整列表,或者这些额外的响应头(由服务器设置)仅在PHP完成后设置很久?
在ASP.NET中工作时,HttpResponse对象有一个DisableKernelCache()方法.例如,HttpHandler可以:
public void ProcessRequest(HttpContext context)
{
context.Response.DisableKernelCache();
...
Run Code Online (Sandbox Code Playgroud)
MSDN有用地将此方法描述为:
禁用当前响应的内核缓存.
我为什么要使用这个功能?
我使用的mojolicious应用程序是基于JSON的,即客户端和服务器之间的交互更多是JSON结构化数据的交换.
我试图在其中一个REST调用期间发生错误时,使用正确的HTTP响应代码实现处理错误的标准方法.实施这样一个标准的最佳方法是什么?我在哪里做?
我看到了几种方法
创建一个类并列出所有错误响应及其相关内容,可以使用响应代码调用此类,该响应代码将返回包含所有相关条目的JSON结构(散列和数组的组合),然后使用render_json控制器中的()方法并将其作为对客户端的响应返回
我可以在数据库中创建一个表,其中包含响应所需的所有字段的条目,使用该字段来访问JSON结构,创建适当的响应并在控制器中使用render_json()并将其作为对客户端的响应返回.
错误响应的示例可能是
Run Code Online (Sandbox Code Playgroud){ "Message": "The requested resource is not found" "Type" : "http://this.is.an.error.com/error/resource_not_found", "ErrorCode" : 404, "Created" : "2012-11-05T11:59:29-05:00", "Request" : "GET /types/Foo/instances" }
标准化此类响应的正确方法是什么?
你能解释一下这段代码的作用:
App.config(['$httpProvider', function ($httpProvider) {
$httpProvider.responseInterceptors.push('HttpSpinnerInterceptor');
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
angular.element('.brand img').attr("src","<%= asset_path('brand/brand.gif') %>");
return data;
});
}]);
App.factory('HttpSpinnerInterceptor', function ($q, $window) {
return function (promise) {
return promise.then(function (response) {
angular.element('.brand img').attr("src","<%= asset_path('brand/brand.png') %>");
return response;
}, function (response) {
angular.element('.brand img').attr("src","<%= asset_path('brand/brand.png') %>");
return $q.reject(response);
});
};
});
Run Code Online (Sandbox Code Playgroud)
我完全没有理解,除了一些猜测,它拦截了一些响应并注入了图像的src属性.
我不明白HttpSpinnerInterceptor是如何以及何时被调用的以及"promise"参数是什么.
我正在尝试使用他们在这里提供的代码实现klarna checkout .
按照此链接的指示实施流程 - > https://docs.klarna.com/en/getting-started
我正在使用docs/examples文件夹中的代码,我已经将库(src文件夹)放在正确的路径中,当我在这里创建一个测试帐户时,已经提供了klarna提供的商店ID和共享密码的eid和共享密钥.
// Merchant ID
$eid = 'eid';
// Shared secret
$sharedSecret = 'sharedsecret';
Run Code Online (Sandbox Code Playgroud)
我已经替换了所有文件中的所有eid和共享scret,并且还正确地更改了文件中的链接,
即example.com到mywebsiteurl.com
$create['purchase_country'] = 'SE';
$create['purchase_currency'] = 'SEK';
$create['locale'] = 'sv-se';
$create['merchant']['id'] = $eid;
$create['merchant']['terms_uri'] = 'http://example.com/terms.html';
$create['merchant']['checkout_uri'] = 'http://example.com/checkout.php';
$create['merchant']['confirmation_uri']
= 'http://example.com/confirmation.php' .
'?sid=123&klarna_order={checkout.order.uri}';
// You can not receive push notification on non publicly available uri
$create['merchant']['push_uri'] = 'http://example.com/push.php' .
'?sid=123&klarna_order={checkout.order.uri}';
Run Code Online (Sandbox Code Playgroud)
正确设置所有内容后,当我单击docs/examples/checkout.php时,我会抛出异常,因为服务器正在响应错误代码.BasicConnector.php通过下面给出的代码抛出异常,
* Throw an exception if the server responds with an error code. …Run Code Online (Sandbox Code Playgroud) 我有这种情况:
点击一个HTML提交按钮,我把views.stream_response它"激活" views.stream_response_generator其"激活" stream.py并返回StreamingHttpResponse,我看到一个渐进的数每秒达m在/stream_response/:
1
2
3
4
5
6
7
8 //e.g. my default max value for m
Run Code Online (Sandbox Code Playgroud)
stream.py
from django.template import Context, Template
import time
def streamx(m):
lista = []
x=0
while len(lista) < m:
x = x + 1
time.sleep(1)
lista.append(x)
yield "<div>%s</div>\n" % x #prints on browser
print(lista) #print on eclipse
return (x)
Run Code Online (Sandbox Code Playgroud)
views.py
def stream_response(request): // unified the three functions as suggested
if request.method == …Run Code Online (Sandbox Code Playgroud) 我正在调用我的Web API HttpClient,我看到有一个EnsureSuccessStatusCode方法和一个IsSuccessStatusCode属性.哪一个合适?
我读了这篇文章,还有一些问题:
使用EnsureSuccessStatusCode并处理它抛出的HttpRequestException
我遇到的问题是,如果我发送一个GET请求,我传递了ID我想要检索的对象,基本上有两个结果:
如果我调用EnsureSuccessStatusCode()状态404将导致抛出异常.这并不理想,因为当我测试我的代码时,我一直收到404错误,这首先让我觉得API URL不正确,但实际上没有匹配的对象与提供的Id.在这种情况下,我宁愿返回一个null对象而不是抛出异常.
所以我尝试检查IsSuccessfulStatusCode属性的值.这似乎是一个更好的选择,当此属性为false时,我可以返回一个null对象,但是,有许多状态代码可能导致此属性具有false值.404是其中之一,但还有其他几个状态代码,例如400 Bad Request,405 Method Not Allowed等.我想记录除404之外的所有不成功的错误代码的异常,我想知道是否有一种更好的方法可以做到这一点,而不是检查ResponseCode响应的值,然后抛出一个由我的catch块捕获的异常,这是记录发生的地方.
这是我的GET方法的代码:
public static Customer GetCustomerByID(int id)
{
try
{
using (var client = GetConfiguredClient())
{
Customer customer = null;
var requestUri = $"Customers/{id}";
using (var response = client.GetAsync(requestUri).Result)
{
if (response.IsSuccessStatusCode)
customer = response.Content.ReadAsAsync<Customer>().Result;
}
return customer;
}
}
catch (Exception ex)
{
ex.Data.Add(nameof(id), id);
LogException(ex);
throw; …Run Code Online (Sandbox Code Playgroud) 在我的Spring API中,我想用Spring的注释@ResponseStatus处理来自诸如create,put和delete之类的操作的响应 .每个端点都能正常工作,但它们始终返回空响应.
为什么来自带注释的端点的响应是空的?
控制器:
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
@RestController
@RequestMapping(value = "/v1/portfolios")
public class PortfolioController {
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Portfolio resource) {
repo.save(resource);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") String id) {
repo.removeById(id);
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用MVC和WebAPI构建一个ASP.NET Core 2.0网站,以提供对一系列微服务的访问.如果WebAPI控制器要求用户进行身份验证和授权(使用该Authorize属性),则任何未经授权或未登录的用户都会将响应作为MVC登录页面的整个HTML获取.
当未经授权的用户访问API时,我想在响应中返回HTTP状态代码401及其相关的错误消息,而不是整个HTML页面.
我已经看了一些现有的问题,并注意到他们要么引用ASP.NET MVC(例如WebApi.Owin中的SuppressDefaultHostAuthentication也禁止webapi之外的身份验证),这对ASP.NET Core 2.0没有好处.或者他们正在使用Core 1.x的hackaround,这似乎不对(ASP.Net核心MVC6重定向到未经授权时登录).
在Core 2.0中是否有适当的解决方案,任何人都知道?如果没有,任何想法如何正确实施?
作为参考,以控制器的一部分为例:
[Authorize]
[ApiVersion("1.0")]
[Produces("application/json")]
[Route("api/V{ver:apiVersion}/Organisation")]
public class OrganisationController : Controller
{
...
[HttpGet]
public async Task<IEnumerable<string>> Get()
{
return await _organisationService.GetAllSubdomains();
}
...
}
Run Code Online (Sandbox Code Playgroud)
以及Statup.cs中的配置:
public void ConfigureServices(IServiceCollection services)
{
...
// Add API version control
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ErrorResponses = new DefaultErrorResponseProvider();
});
// Add and configure MVC services. …Run Code Online (Sandbox Code Playgroud) httpresponse http-status-code-401 asp.net-core-webapi asp.net-core-2.0
httpresponse ×10
httprequest ×2
java ×2
php ×2
rest ×2
angularjs ×1
asp.net ×1
c# ×1
caching ×1
curl ×1
django ×1
django-forms ×1
django-views ×1
http ×1
http-headers ×1
interceptor ×1
magento ×1
member ×1
mojolicious ×1
perl ×1
promise ×1
servlets ×1
spring ×1
spring-mvc ×1
streaming ×1