嗨,我已经开始使用HttpUrlConnection了,我有一个关于何时实际发送Http请求的问题。
我在某个地方读到,当调用getInputStream()时,实际的请求是发送的。不过,我已经编写了一些测试代码,用于处理POST请求:
在这个版本中,我在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()发送的,而是在更早的方法中发送的。有人对此有任何洞察力吗?
谢谢!
发布于 2014-06-19 06:58:21
HttpURLConnection#getResponseCode() - 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()并获得响应代码。
发布于 2014-06-19 06:56:34
getResponseCode()做了同样的事情:它刷新请求并开始读取响应。
实际上,您必须开始读取请求的响应(代码或流),以便将请求完全发送到服务器。
https://stackoverflow.com/questions/24300400
复制相似问题