【发布时间】:2014-03-07 04:00:01
【问题描述】:
我正在尝试将 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();
}
}
【问题讨论】:
-
您是否尝试过使用 fiddler 来查看请求之间的区别?
-
不,我从不使用这种东西。等等,我试试
-
当您从 C# 编写 json 时,它也会写入正斜杠。所以当它在另一边接收时,你必须从字符串中删除它们。
-
实际上服务器不在我们的控制之下。它是一项公共服务。
-
如果需要,您可以使用代理(如 fiddler)拦截 https 流量。或者可能更简单:将您的代码临时指向一个非 https 端点,以便您可以轻松扫描通过网络发送的实际数据。