使用POST请求到吉拉API发送JSON时System.Net.WebException [英] System.Net.WebException when sending JSON using POST request to a Jira API

查看:495
本文介绍了使用POST请求到吉拉API发送JSON时System.Net.WebException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的球员,我一直在摔跤这个问题一天左右,没有明确的解决方案。我会异常启动:

Alright guys, I have been wrestling with this issue for a day or so with no clear resolution. I will start with the exception:

The remote server returned an error: NotFound.
    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

我试图连接到JIRA其余的API用于在用户登录。我们JIRA系统当前运行4.4.1,和我试图打API的信息记录在这里:的 https://developer.atlassian.com/static/rest/jira/4.4.1.html 。 (请参阅/认证/ 1 /会话API POST请求)

I am attempting to connect to the JIRA rest API for logging in a user. Our JIRA system is currently running 4.4.1, and the API information I am attempting to hit is documented here: https://developer.atlassian.com/static/rest/jira/4.4.1.html. (See the POST request for the "/auth/1/session" API)

有关POST请求的API调用,用JSON身体为用户凭据。我曾经尝试都手动构建JSON,以及使用JSON库,结果都是一样的。我送了JSON是:

The API calls for a POST request, with a JSON body for the user credentials. I have tried both building the JSON manually, as well as using a JSON library, and the results were the same. The json I am sending is:

{ 
    "username": "test",
    "password": "test"
}

我试图改变内容类型和编码什么是我能想象。这包括文/ JSON,应用/ JSON的,并补充Encoding.UTF8到流作家,等所有的结果都是一样的。

I have attempted to change the content type and encoding to anything I can imagine. This includes "text/json", "application/json", adding Encoding.UTF8 to the stream writer, etc. All the results are the same.

也许最这整个磨难令人沮丧的是,我能在任何时候都写这在Java中为Android,所以我不相信这是误解,因为有太多作为一款Windows Phone 8和/或C#误解的API。

Perhaps the most frustrating part of this entire ordeal, is that I was able to write this in Java for Android in no time at all, so I do not believe it is an API misunderstanding as so much as a Windows Phone 8 and/or C# misunderstanding.

最后几点事情要指出的:

A few final things to point out:


  • 如果我更改代码以使用GET请求,指向http://www.google.com,并删除请求回调(直接跳到响应),一切正常,我得到的结果我希望。

  • 我的BeginXEndX对于HttpWebRequest方法混淆。我明白了异步任务,但C#只是不完全是如何管理这一点。最MSDN文档的不使用这些,而是​​具有用于方法的GetRequest()和的GetResponse(),这似乎更直截了当。我已经通过筛选最近的例子也使用这些方法。我的假设是,这些方法是在Windows Phone 8 SDK中删除,以确保可以异步运行所做的一切之下。

  • 如果我直接从除Wi​​ndows Phone的任何浏览器击中JIRA网址8模拟器,我得到一个有效的403文档所概述。但是,如果我直接在模拟器命中URL,它提示我要登录凭据。这让我觉得这是需要基本身份验证,所以我也尝试添加了,但我得到了相同的结果。

下面是代码因为我现在有它。我已经采取了我的吉拉主机名

Below is the code as I currently have it. I have taken out my Jira host name

class LoginService
{
    public static UserSession login(string aUsername, string aPassword)
    {
        String loginUrl = "http://{myjiraurl}/rest/auth/1/session/";
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(loginUrl);

        string jsonBody = JsonHelper.GenerateLoginJson(aUsername, aPassword);

        RequestInformation requestInfo = new RequestInformation();
        requestInfo.request = request;
        requestInfo.JsonBody = jsonBody;

        requestInfo.request.Method = "POST";
        requestInfo.request.ContentType = "text/json";
        requestInfo.request.ContentLength = (long)jsonBody.Length;

        request.BeginGetRequestStream(new AsyncCallback(LoginRequestCallback), requestInfo);
        return null;
    }

    private static void LoginRequestCallback(IAsyncResult result)
    {
        RequestInformation requestInfo = (RequestInformation)result.AsyncState;
        HttpWebRequest webRequest = requestInfo.request;

        // End the Asynchronus request.
        Stream requestSream = webRequest.EndGetRequestStream(result);

        StreamWriter requestWriter = new StreamWriter(requestSream);
        requestWriter.Write(requestInfo.JsonBody);
        requestWriter.Flush();
        requestWriter.Close();
        requestSream.Close();

        webRequest.BeginGetResponse(new AsyncCallback(LoginResponseCallback), requestInfo);
    }

    private static void LoginResponseCallback(IAsyncResult result)
    {
        RequestInformation requestInfo = (RequestInformation)result.AsyncState;
        HttpWebRequest webRequest = requestInfo.request;
        try
        {

            HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(result);

            if (response.StatusCode == HttpStatusCode.OK)
            {

                Stream streamResponse = response.GetResponseStream();

                string responseResult = StreamHelper.ReadStreamToString(streamResponse);
                streamResponse.Close();
            }
            response.Close();
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.Message);
            System.Diagnostics.Debug.WriteLine(e.StackTrace);
        }
    }
}

public class RequestInformation
{
    // This class stores the request state of the request and any necessary information for the request body
    public HttpWebRequest request;

    public string JsonBody { get; set; }
    public string Result { get; set; }

    public RequestInformation()
    {
        request = null;
    }
}



编辑:对于一些澄清,代码失败时尝试生成该线路上的响应对象...

For some clarification, the code is failing when attempting to generate the response object on this line...

HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(result);



更新1:

我发现我可以投的引发WebException 的响应到 HttpWebResponse 。这让我看到了什么确切的状态代码,这是 HttpStatusCode.UnsupportedMediaType 或415现在这直接与JSON编码的问题是被发送到分服务器。

I have discovered that I can cast the response of the WebException into an HttpWebResponse. This allowed me to see what the exact status code was, which was HttpStatusCode.UnsupportedMediaType or 415. This now points directly at an issue with the JSON encoding that is being sent to the server.

推荐答案

你们会认为我是个疯子,但大约下午3点,我一直得到预期的结果。

You guys are going to think I am a lunatic, but as of about 3:00pm I have been getting the expected results.

我会编辑这个答案与更新的代码,一旦我重构它一点点。

I will be editing this answer with the updated code once I refactor it a little bit.

更新工作代码:

public static async Task<HttpWebResponse> SendHttpPostRequest(string url, string content, string contentType, string acceptType)
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(url, UriKind.Absolute));
        HttpWebResponse response = new HttpWebResponse();
        string responseText = "";

        request.Method = "POST";
        request.ContentType = contentType;
        request.Accept = acceptType;

        Task<Stream> requestTask = Task.Factory.FromAsync(request.BeginGetRequestStream, asyncResult => request.EndGetRequestStream(asyncResult), (object)null);
        await requestTask.ContinueWith(t =>
        {
            using (Stream stream = requestTask.Result)
            using (StreamWriter requestWriter = new StreamWriter(stream))
            {
                requestWriter.Write(content);
            }
        });

        Task<WebResponse> responseTask = Task.Factory.FromAsync(request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), (object)null);
        await responseTask.ContinueWith(t =>
        {
            try
            {
                response = (HttpWebResponse)responseTask.Result;
            }
            catch (AggregateException ae)
            {
                foreach (Exception e in ae.InnerExceptions)
                {
                    if (e is WebException)
                    {
                        response = (HttpWebResponse)((WebException)e).Response;
                        System.Diagnostics.Debug.WriteLine(e.Message);
                        System.Diagnostics.Debug.WriteLine(e.StackTrace);
                    }
                }
            }
        });

        return response;
    }
}

这篇关于使用POST请求到吉拉API发送JSON时System.Net.WebException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆