在Java中的HTTP请求中添加HEADER [英] Add HEADER in HTTP Request in Java
问题描述
我正在使用以下代码发送简单的HTTP请求:
I'm using this following code to send simple HTTP Request :
try
{
Socket s = new Socket ();
s.bind (new InetSocketAddress (ipFrom, 0));
s.connect (new InetSocketAddress (ipTo, 80), 1000);
PrintWriter writer = new PrintWriter (s.getOutputStream ());
BufferedReader reader = new BufferedReader (new InputStreamReader (s.getInputStream ()));
writer.print ("GET " + szUrl + " HTTP/1.0\r\n\r\n");
writer.flush ();
s .close ();
reader.close ();
writer.close ();
}
但是,如您所见,我没有发送自定义HEADER. 我应该添加什么来发送自定义HEADER?
However, as you can see, I don't send a custom HEADER. What should I add to send a custom HEADER ?
干杯
克里斯托弗·奥利维尔
推荐答案
撰写时
writer.print ("GET " + szUrl + " HTTP/1.0\r\n\r\n");
\r\n\r\n
位正在发送换行/回车以结束该行,然后发送另一个以指示没有更多的标头.这是HTTP和电子邮件格式的标准,即空白行表示标题的末尾.为了添加其他头,您只需要在完成后才发送该序列即可.您可以改为执行以下操作
The \r\n\r\n
bit is sending a line-feed/carriage-return to end the line and then another one to indicate that there are no more headers. This is a standard in both HTTP and email formats, i.e. a blank line indicates the end of headers. In order to add additional headers you just need to not send that sequence until you're done. You can do the following instead
writer.print ("GET " + szUrl + " HTTP/1.0\r\n");
writer.print ("header1: value1\r\n");
writer.print ("header2: value2\r\n");
writer.print ("header3: value3\r\n");
// end the header section
writer.print ("\r\n");
这篇关于在Java中的HTTP请求中添加HEADER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!