编辑:现在我已经找到了一些行为,我想知道,为什么它不会在我调用flush()
或close()
时立即发送请求?为什么要等到我调用getResponseCode()
?
原始问题:
我对java中的HttpsURLConnection类还不太熟悉,在文档上查阅后并没有得到很好的解释。我在一个项目中继承了这段代码(不是我自己写的),想知道它在做什么以及如何改进。例如,我无法确定“writeBytes”是否实际发送数据或者是“close”。我查看了许多javadoc,并发现它们含糊不清,在书籍或在线博客文章中也没有找到关于此主题的好资源。请问有人可以给我指点一下,或者指向一些好的资源吗?
顺便说一句,这段代码是我正在开发的android SDK库。
注意:我非常了解HTTP请求的理论知识。我学过这方面的课程。我知道所有关于URL参数(使用?name=value)和cookies和RESTful服务和TCP和IP等内容。只是在寻找好的文档,以便我知道如何使用java库。
编辑:将此更改为HttpClient代码,因为事实证明我无法使用Https并仍然从回显服务器中查看请求。但它的思想是一样的。
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpClient
{
public static final String DEBUG_URL = "http://10.20.1.61:8001/api/ad/v5/";
public static final String MAPPED_KEYWORDS = "get_mapped_keywords/";
private static byte[] buffer = new byte[1024];
static NetworkReturn sendHttpPost(String urlString, String postData)
{
URL url;
HttpURLConnection con = null;
try {
url = new URL(urlString);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(postData.length()));
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();
StringBuilder result = new StringBuilder(), error = new StringBuilder();
int responseCode = con.getResponseCode();
if (responseCode >= 200 && responseCode < 300)
{
if (con.getInputStream() != null)
{
InputStream in = new BufferedInputStream(con.getInputStream());
int length;
while ((length = in.read(buffer)) != -1)
{
result.append(new String(buffer, 0, length));
}
}
}
else
{
if (con.getErrorStream() != null)
{
InputStream in = new BufferedInputStream(con.getErrorStream());
int length;
while ((length = in.read(buffer)) != -1)
{
error.append(new String(buffer, 0, length));
}
}
}
return new NetworkReturn(responseCode, result.toString(), error.toString());
}
catch (MalformedURLException e) {
return new NetworkReturn(-1, "", "MalformedURLException: " + e.getLocalizedMessage());
}
catch (IOException e) {
e.printStackTrace();
return new NetworkReturn(-1, "", "IOEXCEPTION: " + e.getLocalizedMessage());
}
finally {
if (con != null)
con.disconnect();
}
}
}