![](/img/trans.png)
[英]Java HttpURLConnection VS Android HttpURLConnection
[英]Java - HttpUrlConnection
嗨,我已经开始使用HttpUrlConnection
并且我对实际发送Http请求的时间有疑问。
我读到某个地方,当调用getInputStream()
时发送了实际请求。 但是,我编写了一些测试代码来处理POST请求:
在此版本中,我在getInputStream()
之前调用getResponseCode()
getInputStream()
URL obj = new URL(myUrl);
HttpURLConnection httpclient = (HttpURLConnection) obj.openConnection();
httpclient.setRequestMethod("POST");
**int responseCode = httpclient.getResponseCode();**
try {
inStream = httpclient.getInputStream();
}
catch (IOException ie) {
inStream = httpclient.getErrorStream();
}
System.out.println("response code = " + responseCode);
我收到了200的响应代码。因此,我想到了该请求不是在getInputStream()上发送的,而是在一种较早的方法上发送的。 有人对此有见识吗?
谢谢!
HttpURLConnection#getResponseCode()
Code Insight-openJDK 7
public int getResponseCode() throws IOException {
454 /*
455 * We're got the response code already
456 */
457 if (responseCode != -1) {
458 return responseCode;
459 }
460
461 /*
462 * Ensure that we have connected to the server. Record
463 * exception as we need to re-throw it if there isn't
464 * a status line.
465 */
466 Exception exc = null;
467 try {
468 getInputStream();
469 } catch (Exception e) {
470 exc = e;
471 }
472 ...
基本上, response code
在初始化时将为-1,这意味着我们没有任何响应代码。 因此,它将建立一个连接URL#getInputStream()
并获取响应代码。
getResponseCode()
做同样的事情:它刷新请求并开始读取响应。
实际上,您必须尝试开始读取响应(代码或流),以将请求完全发送到服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.