Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

C# .NET Framework 4.8 API Call not working with New URI

I have an API Post in C# (.NET Framework 4.8) that is working. A new API has been created with a new URI. (I do not have access to the API "Black Box"), When I point the existing code to the new API URI it does not work. I have been given me the following guidance:

 Use a "Content Type" of "text/plain" (the old used "application/xml")
 Add the parameters to the body of the call. (I had this in a querystring in the old version.)

Here is the c# code that works in the current API:

  public static string HttpPost(string URI, string Parameters)
    {
        try
        {
            //URI = System.Configuration.ConfigurationManager.AppSettings["SiteURL"];
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            //req.Proxy = new System.Net.WebProxy(ProxyString, true);
            //Add these, as we're doing a POST
            req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            req.Method = "POST";
            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();
            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null) return null;
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string postXML = sr.ReadToEnd().Trim();
            resp.Close();
            return postXML;
        }
        catch(Exception ex)
        {
            return "could not pull" + ex.Message;
        }
        
    }

Here is the original Java that works in both the old and the new system with only a change needed for "Content-Type" from "application/xml" to "text/plain". :

        HttpURLConnection connection = null;
        URL newUrl = new URL(baseUrl);

        connection = (HttpURLConnection)newUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        /** OLD SYSTEM TAKES "application/xml" FOR "Content-Type" */
        connection.setRequestProperty("Content-Type", "application/xml");
   
        /** NEW SYSTEM REQUIRES "text/plain" FOR "Content-Type" */
        connection.setRequestProperty("Content-Type", "text/plain"); 
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");

---- UPDATE ----

I serialized the content as JSON but still getting a 400 error. I am passing 3 parameters... ENCQS, KS, & DS in the body. My understanding is that if you have a complex object (json) it automatically goes into the body which is where they are saying it has to be. I have little other guidance as this is a 3rd party API in C# that I have no info on. To reiterate, they are moving from one system to another and they tried to "make it easy" so all I would have to do was change my URI. This has been anything but easy (for me) your results (hopefully) will vary... Thanks to all those helping and Thanks in advance to new directions/guidance.:

My API Class:

public class APIParameters
{
    public string ENCQS { get; set; }
    public string KS { get; set; }
    public string DS { get; set; }
    public APIParameters()
    {
        ENCQS = "";
        KS = "";
        DS = "";
    }
}
public class APICall
{ 
    public string URI { get; set; }
    public string ContextType { get; set; } = "application/xml";
    public string Response { get; set; }
    public APIParameters Params = new APIParameters();
    
    public APICall()
    {
        URI = "";
        ContextType = "application/xml";
        Response = "";

    }

}

My new HTTP API Call (that gets a 400 error) I am calling this in such a way that makes it sync thanks to this brilliant piece of code:

HttpResponseMessage response;
string responseMsg = "";

System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
using (var client = new HttpClient())
{
    var content = new StringContent(JsonConvert.SerializeObject(API.Params), Encoding.UTF8, "application/json");
    content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/plain");
    response = await client.PostAsync(URI, content);
    responseMsg = await response.Content.ReadAsStringAsync();
}

Here is the error I am getting

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff X-WebKit-CSP: default-src 'self'
X-Permitted-Cross-Domain-Policies: master-only Connection: close
Transfer-Encoding: chunked Cache-Control: no-cache Date: Wed, 27 Jan 2021 18:04:07 GMT Set-Cookie: visid_incap_2284916=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; expires=Wed, 26 Jan 2022 20:08:03 GMT; HttpOnly; path=/; Domain=.portal.conduent.com; Secure; SameSite=None Set-Cookie: incap_ses_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; path=/; Domain=.My.Domain.com; Secure; SameSite=None Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET
Strict-Transport-Security: max-age=31536000 X-CDN: Incapsula
X-Iinfo: 3-9884384-9884391 NNNN CT(58 122 0) RT(12121212121 51) q(0 0 2 0) r(3 4) U6 Content-Type: text/plain; charset=utf-8 }}

question from:https://stackoverflow.com/questions/65877158/c-sharp-net-framework-4-8-api-call-not-working-with-new-uri

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sometimes it is as simple as flushing your DNS cache in command line: ipconfig /flushdns -for MS Windows.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...