标签: httpresponse

如何从响应中读取文件名-reactJs

我正在从服务器下载文件。我在那里设置一个我想在前端读取的文件名。这是我在服务器上执行此操作的方法:

string fileName = "SomeText" + DateTime.UtcNow.ToString() + ".csv";

return File(stream, "text/csv", fileName);
Run Code Online (Sandbox Code Playgroud)

基本上我会返回不同类型的文件,有时csv有时xlsx有时pdf。所以我想在前端获取文件名,以便我可以将其保存为应有的格式,例如SomeText.pdf它将自动保存在本地计算机上作为pdf.

这是我的前端代码:

getFileFromServer(params).then(response => {
  console.log('server response download:', response);
  const type = response.headers['content-type'];
  const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' });
  //const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = 'file.xlsx'; // Here I want to get rid of hardcoded value instead I want filename from server
  link.click();
  link.remove(); // …
Run Code Online (Sandbox Code Playgroud)

javascript c# httpresponse reactjs asp.net-core

5
推荐指数
1
解决办法
2万
查看次数

使用 Falcon RES API 提供 pdf 文件

我正在尝试使用 Falcon REST API 提供 pdf 文件,但我找不到任何示例。

到目前为止,这是我尝试过的:

class ReportResource:

  def on_get(self, req, resp):
    filename="./evaluation.pdf"
    resp.downloadable_as = filename
    resp.content_type = 'report/pdf'
    resp.status = falcon.HTTP_200
Run Code Online (Sandbox Code Playgroud)

我得到的是一个空的pdf文件,当然我无法打开。我猜我没有在响应中加载文件内容,但我不是 python 专家,我不知道应该如何做。

如果我尝试这个:

resp.stream, resp.stream_len = open(filename)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 130: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

我完全确定该文件就在那里。

python rest httpresponse falconframework

5
推荐指数
1
解决办法
1039
查看次数

如何使用批处理脚本调用的curl 获取http post 请求的响应代码?

我正在努力为从我们的工具之一发送 http post 请求提供支持。该工具基本上通过 http 请求执行作业。

实现此目的的方法是该工具使用多个参数调用 RunScript.bat。该脚本解析这些参数并在验证后发出curl post 请求。Post 请求由我们内部的 Java 服务处理。

我想要的是我的批处理文件应该能够获取发布请求的响应代码(200/409 等),并且基于此,脚本应该返回 1 或 0 作为退出值返回到工具。然后,该工具根据返回值标记作业通过/失败。

工具:解析返回值

RunScript.bat arg1 arg2 arg3

运行脚本.bat

@echo off
SETLOCAL
ECHO %DATE% %TIME% Calling %0 with %*
SET "SCRIPT_DIR=%~dp0"
ECHO Script Dir %SCRIPT_DIR%
SET cmd=%1
SET val2=%2
SET val3=%3

%SCRIPT_DIR%\curl -v -X POST http://localhost:9500/%cmd%/%val2%/%val3%
Run Code Online (Sandbox Code Playgroud)

是否可以在批处理脚本中获取curl请求的Response Code,然后根据Response Code返回1/0?

curl http batch-file httpresponse return-value

5
推荐指数
1
解决办法
1万
查看次数

Angular 测试:模拟包含 blob 的 HttpResponse

我正在开发 Angular 9 应用程序,并且正在编写单元测试,这要归功于 jest。我的 Angular 服务调用 Spring API,该 API 返回 CSV 文件以供下载。我想进行单元测试,但无法模拟 HttpResponse。

* MyService.ts *

downloadCsv(id: string) {
    return this.http.get('/api/ + id + `/csv/`,
      { responseType: 'blob' as 'json', observe: 'response' });
  }
Run Code Online (Sandbox Code Playgroud)

* MyService.spec.ts *

  it(`should call the GET API and return a csv file as result`, () => {
    // GIVEN 
    const expectedData: Blob = new Blob(['a', 'b', 'c', 'd']);

    // WHEN
    let actualData = {};
    service.downloadCsv('1').subscribe(data => {
      actualData = data;
    });

    // THEN
    backendMock.expectOne((req: …
Run Code Online (Sandbox Code Playgroud)

unit-testing blob httpresponse jestjs angular

5
推荐指数
1
解决办法
1万
查看次数

如何修改fetch API中请求对象的url?

我正在使用由 HTTP 请求触发的 Cloudflare Worker。我想接受传入请求,更改 url 但保持所有其他属性不变,然后发出请求。结构如下:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch(request)
    .then(response => {
        return response;
    });
}
Run Code Online (Sandbox Code Playgroud)

javascript http httpresponse httprequest fetch

5
推荐指数
2
解决办法
3940
查看次数

在 Polly 库中使用 httpclient 的指数退避

我刚刚读到Polly 库,当从桌面代理到服务器通信时,我需要处理 3 次重试。

目前我喜欢指数退避。

但是,我很难理解如何在我的代码中实现这一点。这是我到目前为止所做的:

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
    client.DefaultRequestHeaders.Add("TenantId", tenantId);
#if DEBUG
    var url = "http://localhost:5001/api/v1/RetrievePaymentDetails?orderpaymentid={orderPaymentId";
#else
    //TODO: add URL once the application is in production!
    var url = "intent2.api";
#endif
    Policy
        .Handle<HttpRequestException>()
        .WaitAndRetry(new[]
        {
            TimeSpan.FromSeconds(5),
            TimeSpan.FromSeconds(15),
            TimeSpan.FromSeconds(30)
        });

    using (HttpResponseMessage response = await client.GetAsync($"{url}"))
    {
        using (HttpContent content = response.Content)
        {
            HttpContentHeaders headers = content.Headers;
            var result = JsonConvert.DeserializeObject<PaymentDetailsDto>(response.Content.ReadAsStringAsync().Result);
            Currency currencyFromDb = (Currency)Enum.Parse(typeof(Currency), result.Currency);
            var result2 = …
Run Code Online (Sandbox Code Playgroud)

c# httpresponse dotnet-httpclient polly retry-logic

5
推荐指数
2
解决办法
6780
查看次数

中间件清除响应内容

在管道的顶部Startup.Configure,我创建了一个自定义中间件,它处理我的 asp net core 应用程序的错误,如下所示:

public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception)
        {
            if (context.Response.StatusCode != (int)HttpStatusCode.ServiceUnavailable && context.Response.StatusCode != (int)HttpStatusCode.InternalServerError)
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
        }
        finally
        {
            if (context.Response.StatusCode / 100 != (int)HttpStatusCode.OK / 100)
            {
                string message = ((HttpStatusCode)context.Response.StatusCode) switch
                {
                    HttpStatusCode.ServiceUnavailable => "The application is currently on maintenance. Please try again later.", …
Run Code Online (Sandbox Code Playgroud)

c# httpresponse asp.net-core-middleware asp.net-core-3.1

5
推荐指数
1
解决办法
3197
查看次数

何时使用 ResponseStatusException 和 ControllerAdvice

Spring 5 引入了 ResponseStatusException,这让我陷入了困境,不知道在什么情况下可以使用 ResponseStatusException 和 ControllerAdvice,因为它们非常相似。

谁能帮我这个?

error-handling exception response httpresponse controller-advice

5
推荐指数
1
解决办法
5455
查看次数

有没有办法在Android中找到HTTP请求和响应的完整大小(用于数据使用跟踪)?

我想跟踪我的应用程序的数据使用,但要做到这一点,我需要能够得到的全尺寸HttpUriRequest和HttpResponse.简单地获取大小HttpEntity是不够的,因为请求和响应都传输了更多数据(标题,参数,传输的实际URL等).那么,有没有办法找到双向传输的全部数据?

谢谢.

java android http httpresponse httprequest

4
推荐指数
1
解决办法
3294
查看次数

改善CFHTTP响应时间

我有一个登录帐户的API,然后通过CFHTTP请求搜索我想要出价的项目,如下所示.

Search.cfm:

<cfinclude template="logMeIn.cfm" />

<cfhttp url="https://utas.fut.ea.com/ut/game/fifa14/transfermarket?maxb=1800000&start=0&num=16&type=player&maskedDefId=158023" method="POST" result="Get">
    <cfhttpparam type="header" name="Cache-Control" value="no-cache" />
    <cfhttpparam type="header" name="Host" value="utas.fut.ea.com" />
    <cfhttpparam type="header" name="Referer" value="http://cdn.easf.www.easports.com/soccer/static/flash/futFifaUltimateTeamPlugin/FifaUltimateTeam.swf" />
    <cfhttpparam type="header" name="X-HTTP-Method-Override" value="GET" />
    <cfhttpparam type="header" name="X-UT-PHISHING-TOKEN" value="#ListLast(Session.searchAccount40PhishingKey,'=')#" />
    <cfhttpparam type="header" name="X-UT-SID" value="#Session.searchAccount40SessionKey#" />
</cfhttp>
Run Code Online (Sandbox Code Playgroud)

logMeIn.cfm:

<cfscript>
    Variables.email = "XYZ@example.com";
    Variables.password = "password";
    Variables.secretAnswer = "secretAnswer";
    Session.searchAccountGamertag = "WirierJupiter11";
    Variables.doReload = 0;
    Variables.deviceView = "device=not_mobile";
</cfscript>

<cfhttp url="http://www.easports.com/uk/fifa/football-club/ultimate-team" method="GET" result="stage1" redirect="false">
    <cfhttpparam type="header" name="Accept" value="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" />
    <cfhttpparam type="header" name="Accept-Encoding" value="gzip, deflate" />
    <cfhttpparam type="header" name="Accept-Language" …
Run Code Online (Sandbox Code Playgroud)

coldfusion web-services httpresponse httprequest cfhttp

4
推荐指数
1
解决办法
1256
查看次数