c# - Java 与 C# 带有 JSON 数据的 HTTP 请求

标签 c# java http-post

我正在尝试将 Java 程序转换为 C# 程序。该程序使用 HTTP POST 将 JSON 对象发送到服务器。 Java程序运行良好。返回 200。但是 C# 程序返回 400(错误请求)。可能是什么原因

Java 代码

String base_url = "https://test-url.com";
String username = "test-user";
String password = "test-pass";
String client_id = "test-client";
String client_secret = "test-key";
String loginUrl = base_url + "session/login";

Charset utf8 = Charset.forName("UTF-8");
ContentType jason_content_type = ContentType.create("application/json", utf8); 
try {
    HttpClient c = HttpClients.custom().setUserAgent(client_id + "/1.0").build();
    HttpPost p = new HttpPost(loginUrl);
    String json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
    p.setEntity(new StringEntity(json_str, jason_content_type));
    HttpResponse r = c.execute(p);
    int status = r.getStatusLine().getStatusCode(); 
} catch (IOException e) {
    System.out.println(e);
}

C# 代码

    string base_url = "https://test-url.com";
    string username = "test-user";
    string password = "test-pass";
    string client_id = "test-client";
    string client_secret = "test-key";
    string login_url = base_url + "session/login";

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(login_url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = WebRequestMethods.Http.Post;
    httpWebRequest.UserAgent = client_id + "/1.0";
    httpWebRequest.ProtocolVersion=HttpVersion.Version11;

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
    {
    string json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
    streamWriter.Write(json_str);
    streamWriter.Flush();
    streamWriter.Close();

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
      var result = streamReader.ReadToEnd();
    }
}

最佳答案

尝试在 C# 中添加:

httpWebRequest.ContentType = "application/x-www-form-urlencoded";

关于c# - Java 与 C# 带有 JSON 数据的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241191/

相关文章:

c# - 如何合并两个对象,覆盖空值

c# - ASP.NET MVC 4 中的 Global.asax.cs 文件采用什么模式?

java - Maven javadoc :javadoc works but javadoc:aggregate throws errors that look like compiler errors

c++ - 使用 C++ Winsock API 上传 PNG 文件(HTTP POST)

ssl - 将数据发布到 HTTPS 页面

c# - 如何只查找同时具有 getter 和 setter 的属性?

c# - 使用统一解析具有多个构造函数的实例

java - Minecraft 插件错误

java - 无法添加 JFrame 和 JTextField

java - Android,POST JSON 数组,php 调试