HTTP-запрос Java против C# с данными JSON

Я пытаюсь конвертировать Java-программу на C#. Эта программа отправила объект JSON на сервер с помощью HTTP POST. Программа на Java работает нормально. return 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();
    }
}

1 ответ

Попробуйте добавить в C#:

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
Другие вопросы по тегам