首页 > 解决方案 > 从 api 网站下载 .json 时出现 ResponseStatusLine 错误

问题描述

我一直在尝试使用 Discogs API 制作一个小型应用程序供个人使用,以搜索个人艺术家及其专辑,到目前为止,该应用程序使用非官方的 Discogs C# 应用程序。现在的问题是,我可以提取专辑曲目列表的唯一方法是使用从每个专辑请求中获得的资源 URL(例如,https://api.discogs.com/releases/2890373)。

我尝试从每个 URL 中提取 .json,即使使用适当的标头,我也会不断收到 ResponseLine 错误。

使用我的消费者密钥和密钥添加了授权标头,例如:

httpWebRequest.Headers.Add("Authorization", "Discogs key=xxx, secret=yyy");

...添加了一个 UserAgent,但它仍然无法正常工作。

我在 Python 中尝试过同样的方法,并且效果很好,但我不想每次想要关于专辑的信息时都运行 Python 应用程序。

private void scrape_button_Click(object sender, EventArgs e) {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.discogs.com/releases/2890373");
            httpWebRequest.Method = WebRequestMethods.Http.Get;
            httpWebRequest.Timeout = 12000;
            httpWebRequest.ContentType = "application/vnd.discogs.v2.html+json";
            httpWebRequest.Headers.Add("UserAgent", "matija_search/0.1");
            string file;
            var response = (HttpWebResponse)httpWebRequest.GetResponse();
            using(var sr = new StreamReader(response.GetResponseStream())) {
                file = sr.ReadToEnd();
            }
        }

这是尝试获取数据的按钮。

import requests
import json
info = requests.get('https://api.discogs.com/releases/2890373')
data = info.json()
with open('data.json', 'w') as f:
    json.dump(data, f)

这是一个实际有效的python等价物......

标签: c#jsonapiheaderhttprequest

解决方案


好的,解决了问题。我没有以正确的方式添加 UserAgent。固定代码如下:

private void scrape_button_Click(object sender, EventArgs e) {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.discogs.com/releases/2890373");
            httpWebRequest.Method = WebRequestMethods.Http.Get;
            httpWebRequest.Accept = "application/vnd.discogs.v2.html+json";
            httpWebRequest.UserAgent = "matija_search/1";
            string file;
            var response = (HttpWebResponse)httpWebRequest.GetResponse();
            using(var sr = new StreamReader(response.GetResponseStream())) {
                file = sr.ReadToEnd();
            }
            var contentsToWriteToFile = JsonConvert.SerializeObject(file);
            TextWriter writer = new StreamWriter("test.json", false);
            writer.Write(contentsToWriteToFile);
        }

推荐阅读