我有一个控制器方法来处理ajax调用并返回JSON.我正在使用json.org的JSON库来创建JSON.
我可以做以下事情:
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String getJson()
{
JSONObject rootJson = new JSONObject();
// Populate JSON
return rootJson.toString();
}
Run Code Online (Sandbox Code Playgroud)
但是将JSON字符串放在一起是有效的,只是让Spring将它写入响应的输出流.
相反,我可以将它直接写入响应输出流,如下所示:
@RequestMapping(method = RequestMethod.POST)
public void getJson(HttpServletResponse response)
{
JSONObject rootJson = new JSONObject();
// Populate JSON
rootJson.write(response.getWriter());
}
Run Code Online (Sandbox Code Playgroud)
但似乎有一个更好的方法来做到这一点,而不是诉诸于传递HttpServletResponse给处理程序方法.
是否有另一个类或接口可以从我可以使用的处理程序方法返回,以及@ResponseBody注释?
我写了一个简单的httprequest /响应代码,我得到以下错误.我在类路径中引用了httpclient,httpcore,common-codecs和common-logging.我是java的新手,不知道这里发生了什么.请帮我.
码:
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
public class UnshorteningUrl {
public static void main(String[] args) throws Exception
{
HttpGet request=null;
HttpClient client = HttpClientBuilder.create().build();
try {
request = new HttpGet("trib.me/1lBFzSi");
HttpResponse httpResponse=client.execute(request);
Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
// Preconditions.checkState(headers.length == 1);
String newUrl = headers[0].getValue();
System.out.println("new url" + newUrl);
} catch (IllegalArgumentException e) {
// TODO: handle exception
}finally {
if (request != null) {
request.releaseConnection();
}
}
}}
Run Code Online (Sandbox Code Playgroud)
错误:
Exception in …Run Code Online (Sandbox Code Playgroud) 在web api 2中,我们习惯于使用字符串内容来获取响应:
var response = Request.CreateResponse(HttpStatusCode.Ok);
response.Content = new StringContent("<my json result>", Encoding.UTF8, "application/json");
Run Code Online (Sandbox Code Playgroud)
如何在不使用像ObjectResult这样的内置类的情况下在ASP.NET 5/MVC 6中实现相同的功能?
我正在使用Selenium Remote WebDriver.我从csv文件中读取所有链接并对这些链接运行测试.但有时我得到404回应.
在Selenium WebDriver中是否有任何方法可以检查我们是否获得了HTTP响应200?
是否有可能BadRequest在django中提出异常?
我已经看到你可以筹集404 [1].
用例:在helper方法中,我从request.GET加载一个json.如果json因为浏览器(IE)切断网址而被切断,我想提出一个匹配的异常.
BadRequest异常看起来合适,但到目前为止在django中似乎没有这样的异常.
在1.6中有一个SuspiciousOperation异常.但这与我的情况不符,因为它与安全无关.
当然,我可以尝试一下try ..除了在我的帮助方法中查看方法,但这不是DRY.
有人一个解决方案,我不需要try..exception围绕我的帮助方法的每次调用?
[1] https://docs.djangoproject.com/en/1.6/ref/exceptions/#django.core.urlresolvers.Resolver404
更新
代码示例:
def my_view(request):
data=load_data_from_request(request) # I don't want a try..except here: DRY
process_data(data)
return django.http.HttpResponse('Thank you')
def load_data_from_request(request):
try:
data_raw=json.loads(...)
except ValueError, exc:
raise BadRequest(exc)
...
return data
Run Code Online (Sandbox Code Playgroud) Django 1.7引入了JsonResponse对象,我试图用它来返回我的ajax请求的值列表.
我想通过
>>> Genre.objects.values('name', 'color')
[{'color': '8a3700', 'name': 'rock'}, {'color': 'ffff00', 'name': 'pop'}, {'color': '8f8f00', 'name': 'electronic'}, {'color': '9e009e', 'name': 'chillout'}, {'color': 'ff8838', 'name': 'indie'}, {'color': '0aff0a', 'name': 'techno'}, {'color': 'c20000', 'name': "drum'n'bass"}, {'color': '0000d6', 'name': 'worldmusic'}, {'color': 'a800a8', 'name': 'classic'}, {'color': 'dbdb00', 'name': 'hiphop'}]
Run Code Online (Sandbox Code Playgroud)
到JsonResponse对象.
但是,我的尝试失败了.
>>> JsonResponse({'foo': 'bar', 'blib': 'blab'}) # works
<django.http.response.JsonResponse object at 0x7f53d28bbb00>
>>> JsonResponse(Genre.objects.values('name', 'color')) # doesn't work
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/marcel/Dokumente/django/FlushFM/env/lib/python3.4/site-packages/django/http/response.py", …Run Code Online (Sandbox Code Playgroud) 在我的Django应用程序中,我想跟踪响应是否已成功发送到客户端.我很清楚在像HTTP这样的无连接协议中没有"防水"方式来确保客户端已经接收(并显示)了响应,所以这不是关键任务功能,但我仍然希望在最新的可能时间.响应将不是HTML,因此任何来自客户端的回调(使用Javascript或IMG标签等)都是不可能的.
我能找到的"最新"钩子是在中间件列表的第一个位置添加一个实现process_response的自定义中间件,但根据我的理解,这是在构造实际响应并发送到客户端之前执行的.Django中是否有任何钩子/事件在响应成功发送后执行代码?
我想从我的web api控制器下载一个zip文件.它正在返回文件但我收到一条消息,当我尝试打开时,zipfile无效.我已经看过其他关于此的帖子,响应是添加了responseType:'arraybuffer'.仍然不适合我.我也没有在控制台中出现任何错误.
var model = $scope.selection;
var res = $http.post('/api/apiZipPipeLine/', model)
res.success(function (response, status, headers, config) {
saveAs(new Blob([response], { type: "application/octet-stream", responseType: 'arraybuffer' }), 'reports.zip');
notificationFactory.success();
});
Run Code Online (Sandbox Code Playgroud)
api控制器
[HttpPost]
[ActionName("ZipFileAction")]
public HttpResponseMessage ZipFiles([FromBody]int[] id)
{
if (id == null)
{//Required IDs were not provided
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
}
List<Document> documents = new List<Document>();
using (var context = new ApplicationDbContext())
{
foreach (int NextDocument in id)
{
Document document = context.Documents.Find(NextDocument);
if (document == null)
{
throw new HttpResponseException(new …Run Code Online (Sandbox Code Playgroud) httpresponse zipfile asp.net-web-api angularjs pushstreamcontent
如何在快递4.14中发送状态和消息?
对于:res.sendStatus(200);
我在浏览器上运行正常但我希望它能显示一条自定义消息,例如: 成功1
res.sendStatus(200);
res.send('Success 1');
Run Code Online (Sandbox Code Playgroud)
错误:
错误:发送后无法设置标头.
如果我做这个:
res.status(200).send(1);
Run Code Online (Sandbox Code Playgroud)
错误:
express deprecated res.send(status):改为使用res.sendStatus(status)
有任何想法吗?
当一个System.Web.HttpResponse.End()被调用时,System.Thread.Abort被触发,我猜是(或触发)异常?我有一些日志记录,这是在日志文件中列出的...
第一次机会
exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
12/14/2008 01:09:31::
Error in Path :/authenticate
Raw Url :/authenticate
Message :Thread was being aborted.
Source :mscorlib
Stack Trace : at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort(Object stateInfo)
at System.Web.HttpResponse.End()
at DotNetOpenId.Response.Send()
at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider()
at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108
at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69
TargetSite :Void AbortInternal()
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL
An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was …Run Code Online (Sandbox Code Playgroud) httpresponse ×10
django ×3
python ×2
angularjs ×1
asp.net ×1
c# ×1
django-views ×1
express ×1
http ×1
httpclient ×1
java ×1
json ×1
node.js ×1
spring ×1
spring-mvc ×1
thread-abort ×1
zipfile ×1