简体   繁体   English

为什么将 C# HTTP 请求转换为 Java 不起作用?

[英]Why converting C# HTTP Request to Java did not work?

I am trying to use the Microsoft Custom Vision know more .我正在尝试使用 Microsoft Custom Vision 了解更多信息 I need to make an HTTP request to send the image to be analyzed.我需要发出一个 HTTP 请求来发送要分析的图像。 I successfully made a request from C# so I know the information is correct.我成功地从 C# 发出请求,所以我知道信息是正确的。

However, when I tried to make the same request in Java I received an HTTP 400 error.但是,当我尝试在 Java 中发出相同的请求时,我收到了 HTTP 400 错误。

I believe I did not handle the request correctly in Java.我相信我没有在 Java 中正确处理请求。 Is that true?真的吗?

Following are the snippets.以下是片段。

C#: C#:

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Prediction-Key", PredicitionKey);
using (var content = new 
ByteArrayContent(byteData))
{
  content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  response = await client.PostAsync(url, content);
  Console.WriteLine(await response.Content.ReadAsStringAsync());
}

Java:爪哇:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Prediction-Key", predicitionKey);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.getOutputStream().write(data.getData());
connection.connect();

Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

First, replace首先,更换

connection.connect();

with

connection.getResponseCode();

If it still doesn't work, then the headers are the problem.如果它仍然不起作用,那么标题就是问题所在。

Since C# code runs successfully由于 C# 代码运行成功

The only difference between your C# request and Java one in fiddler is that Java request has two additional headers (Accept, User-Agent).您的 C# 请求和 Fiddler 中的 Java 请求之间的唯一区别是 Java 请求有两个额外的标头(Accept、User-Agent)。

Try setting them explicitly尝试明确设置它们

connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");

If still doesn't work, try removing these two headers or check data you're sending in request body.如果仍然不起作用,请尝试删除这两个标头或检查您在请求正文中发送的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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