标签: httpresponse

将 HTTPResponse 对象转换为字典

我正在尝试将这个对象变成我可以在我的程序中使用的东西。我需要将消息 ID 存储到数据库中。除了彻底解析它之外,我可以以某种方式将整个事情变成一本字典吗?

这是我进行一些 IDLE 测试的地方:

>>> response = urllib.request.urlopen(req)
>>> response.getheaders()
[('Server', 'nginx/1.6.0'), ('Date', 'Sat, 07 Jun 2014 00:32:45 GMT'), ('Content-Type', 'application/json;charset=ISO-8859-1'), ('Transfer-Encoding', 'chunked'), ('Connection', 'close'), ('Cache-Control', 'max-age=1')]
>>> response.read()
b'{"message-count":"1","messages":[{"to":"11234567890","message-id":"02000000300D8F21","status":"0","remaining-balance":"1.82720000","message-price":"0.00620000","network":"302220"}]}'
Run Code Online (Sandbox Code Playgroud)

经过半小时的谷歌筛选后,我能够将其转换为字符串:

>>> response.response.decode('utf-8')
>>> print(response)
'{"message-count":"1","messages":[{"to":"11234567890","message-id":"02000000300D8F21","status":"0","remaining-balance":"1.82720000","message-price":"0.00620000","network":"302220"}]}'
>>> type(response)
<class 'str'>
Run Code Online (Sandbox Code Playgroud)

我找到了这篇文章,但这是我得到的:

>>> a_dict = dict([response.strip('{}').split(":"),])
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
  a_dict = dict([response.strip('{}').split(":"),])
ValueError: dictionary update sequence element #0 has length 9; 2 is required
Run Code Online (Sandbox Code Playgroud)

也许我对这一切的看法都是错误的。将这个对象变成字典或其他我可以轻松使用的东西的最快方法是什么?

python dictionary httpresponse python-3.x

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

Spring - 从过滤器返回 JSON 格式的错误消息

我正在开发 Spring Boot REST 应用程序。

我注册了一个自定义 AuthenticationEntryPoint,如果用户不提供凭据,它会返回“401 未经授权”错误。

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
Run Code Online (Sandbox Code Playgroud)

这非常有效,并返回 JSON 格式的DefaultErrorAttributes,如下所示:

{
  "timestamp": 1465230610451,
  "status": 401,
  "error": "Unauthorized",
  "exception": "org.springframework.security.authentication.BadCredentialsException",
  "message": "Unauthorized",
  "path": "/webapp/login"
}
Run Code Online (Sandbox Code Playgroud)

Filter现在我已经使用以下覆盖添加到应用程序中doFilter()

@ Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
    try {
        // Here be some code that fails.
    } catch (Exception e) …
Run Code Online (Sandbox Code Playgroud)

spring json httpresponse servlet-filters spring-boot

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

从 HttpEntity 获取 JSON

我正在使用 akka.http.scaladsl.model.HttpResponse、HttpEntity。

得到 response 后,它是格式的 responseEntity 类型 (Content-type: 'application/json', {MyJSONHERE})。有没有办法从实体中提取我的json。

我尝试了 entity.getDataBytes ,它以 ByteString 格式提供实体的内容。我想正确读取 JSON 并解析它。有人可以指导我吗?

json scala httpresponse akka httpentity

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

RESTful POST 响应

我有一个非常简单的 RESTful 服务,它通过 POST 接收一些表单数据,其目的是简单地将文本正文(具有唯一的 id)保留在云存储(Amazon S3、Azure Blob 存储等)中作为文件...

所以,问题是..如果一切都很好,并且我向调用者返回 200 响应,那么我应该以正文形式向调用者返回什么?

任何事物?没有什么?

如果这是创建数据库记录..也许该新记录的 id 可能有用..但在这种情况下,我认为简单的 HttpRepsone 代码就足够了?

有人同意、不同意或有支持讨论的链接吗?

我应该补充一点,对该服务的请求几乎是......移交,然后去......他们实际上并不需要我建议发回的唯一ID......这更多的是为了“完整性”。

rest httpresponse httprequest

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

不支持中文的 Content-Disposition 文件名

我一直在尝试下载带有中文文件名的附件,但不知何故他们的编码在下载时发生了变化,并且在有中文字符的地方保存了一些乱码文件名。

技术:Java 服务器:Apache Tomcat

这是我已经尝试过的

response.setHeader("Content-Disposition", "attachment; filename=\"7_6_4_AM__2017_JS_003_??????_B1_108\"");

输出(下载的附件名称):“7_6_4_AM__2017_JS_003_W_äð”

我还尝试在引用后将 * 附加到文件名指令:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition response.setHeader("Content-Disposition", "attachment; filename*=\"7_6_4_AM__2017_JS_003_??????_B1_108\"");

输出(下载的附件名称):“706.txt”

还,

在我的研究中,我发现 HTTP 标头消息不能携带 ISO-8859-1 字符集之外的字符。

https://tools.ietf.org/html/rfc5987

提前致谢。

java file httpresponse character-encoding http-headers

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

如何从 angular http 的响应中读取状态?

我在从响应中读取状态代码时遇到了一些问题。

我在服务中调用 api,

return this.http.get<string>( this.remoteServer + '/google.com/open', httpOptions);
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我有,

open() {
    this.openService.open(this.selected.qrCode)
    .subscribe(
      data => {
       console.log(data);
       this.toastService.showSuccess('Unlock Successfull', 'success');
      }
    );
  }
Run Code Online (Sandbox Code Playgroud)

现在我想阅读 http 状态文本,

我从上述调用中得到的示例 http 响应是。

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: " https://google.com/open ", ok: false, ...}

如何读取控制器中的状态文本。

请帮我

httpresponse http-headers angular angular-httpclient

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

NestJS 从 GridFS 返回一个文件

我正在尝试使用我的 Nest 控制器从 GridFS 返回一个文件。据我所知,nest 不尊重我content-type设置的自定义标头application/zip,因为我在返回时收到了文本内容类型(请参见屏幕截图)。

响应数据图像,错误的内容类型标头

我的巢控制器看起来像这样

  @Get(':owner/:name/v/:version/download')
  @Header('Content-Type', 'application/zip')
  async downloadByVersion(@Param('owner') owner: string, @Param('name') name: string, @Param('version') version: string, @Res() res): Promise<any> {
    let bundleData = await this.service.getSwimbundleByVersion(owner, name, version);
    let downloadFile = await this.service.downloadSwimbundle(bundleData['meta']['fileData']['_id']);   
    return res.pipe(downloadFile);
  }
Run Code Online (Sandbox Code Playgroud)

这是服务电话

downloadSwimbundle(fileId: string): Promise<GridFSBucketReadStream> {
      return this.repository.getFile(fileId)
    }
Run Code Online (Sandbox Code Playgroud)

这本质上是对此的传递。

  async getFile(fileId: string): Promise<GridFSBucketReadStream> {
    const db = await this.dbSource.db;
    const bucket = new GridFSBucket(db, { bucketName: this.collectionName });
    const downloadStream = bucket.openDownloadStream(new ObjectID(fileId));

    return new Promise<GridFSBucketReadStream>(resolve …
Run Code Online (Sandbox Code Playgroud)

zip get httpresponse http-headers nestjs

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

如何从NodeJS中的单个azure函数向azure服务总线和事件发送消息到事件中心总线?

我有一个 azure 函数,它发出一个基于 Promise 的 http post 请求并得到响应;现在我想将此响应发送到服务总线和不同的事件中心(azure 函数由不同的事件中心触发)。

函数表示在事件中心的情况下它已成功执行,但没有发送任何事件。在服务总线的情况下,我收到此错误NamespaceConnectionString should not contain EntityPath.

module.exports = async function (context, eventHubMessages) {
    context.log(`JavaScript eventhub trigger function called for message array ${eventHubMessages}`);

    var completeData = '';

    eventHubMessages.forEach((message, index) => {
        context.log(`Processed message ${message}`);
        completeData = message;
    });

    var output = '';

    const axios = require('axios');

    try {
        const response =  await axios.post('http://fake-endpoint', 
        {  data-json : completeData
        })
        context.log(`statusCode: ${response.statusCode}`);
        context.log(response.data);
        output += response.data;

        var time = new Date().toString(); 
        context.log('Event Hub message …
Run Code Online (Sandbox Code Playgroud)

httpresponse node.js azureservicebus azure-eventhub azure-functions

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

即使请求失败,HTTP 响应始终返回响应代码 200,并且返回状态代码是 REST 的一部分

我最近加入了一个新项目。在这个项目中,服务中的所有 API 总是返回状态代码 200。即使响应应该是 400 或 404,API 也会返回状态代码 200。

我问了 API 不返回其他响应代码的原因,程序员告诉我他们不使用响应代码。他们将信息放入体内。

例如,缺少一些必填字段,它们返回响应状态代码 200,但正文返回这样

{"result" : "fail"}
Run Code Online (Sandbox Code Playgroud)

如果未经授权的用户尝试访问,状态码为 200,则正文返回如下

{"result" : "unautherized"}
Run Code Online (Sandbox Code Playgroud)

我之前所做的非常不同,我总是按案例指定状态代码并尝试返回合适的状态代码和消息。我认为这是 HTTP 协议的一部分。但是,他们告诉我,像 400、404、300 这样的指定状态代码是 RESTful API 的一部分,并且始终返回 200 是正确的状态代码,因为服务器响应并且它处于活动状态。APIs,除了500,总是要返回200。因为当服务器挂掉时,它不能返回任何东西。

所以这些是问题。

  1. 服务器应该总是返回状态代码 200 除非服务器死机?
  2. 指定各种状态代码是 REST API 的一部分吗?
  3. 不使用状态码很常见吗?

rest http conventions httpresponse http-status-codes

4
推荐指数
2
解决办法
7521
查看次数

Spring Boot @ResponseStatus not returning HTTP message

I've a problem returning HTTP Messages when an exception is thrown. I'm using @ResponseStatus annotation to handle the HTTP Status code, it shows ok but the message is ignored.

Custom Exception:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "An error ocurred while trying to 
retrieve the instruments.")
public class InstrumentsNotFoundException extends RuntimeException { 

private static final Logger logger = LoggerFactory.getLogger(InstrumentsNotFoundException.class);

public InstrumentsNotFoundException(String errorMessage) {
    super(errorMessage);
    logger.error(errorMessage);
}
Run Code Online (Sandbox Code Playgroud)

Controller:

@GetMapping({ "/portfolio/" })
public List<Instrument> getAll() {
    try {
        List<Instrument> instruments= portfolioYieldProcessor.getPortfolio();
        return instruments; …
Run Code Online (Sandbox Code Playgroud)

error-handling spring-mvc httpresponse spring-boot

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