简体   繁体   中英

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 }}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM