get源码:
String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=abcdefg";
URL url = new URL(httpUrl);// Open connection using HttpURLConnection
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// Get the content to read (stream)
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());// Create BufferedReader for output
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;// Use a loop to read the obtained data
String resultData = "";
while ((inputLine = buffer.readLine()) != null) {
resultData += inputLine + "";
}// Close InputStreamReader
in.close();// Close the HTTP connection
urlConn.disconnect();
看不懂的小伙伴可以查阅上期文章
大概解释一下过程:首先通过openconnection建立url连接→通过getinputstream获取字节流→通过inputstream获取字符流→然后将字符流传递给缓冲区,这边缓冲区的作用是避免I/O频发操作影响整个网络环境方便接收数据→然后就遍历出来就好了~
注:这边默认的请求方式是get请求,如果是post还有设置一下参数urlConn.setRequestMethod("POST");
下面是post:
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
URL url = new URL(httpUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// Set the request method to POST
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.connect();DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312"); // Parameters to be uploaded
out.writeBytes(content); // Write the content to be uploaded into the stream
out.flush();
out.close();// Get data
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine = null;
String resultData = "";
while ((inputLine = reader.readLine()) != null) {
resultData += inputLine + "";
}
reader.close();
urlConn.disconnect();
我只对post特有代码做解释:
urlConn.setDoOutput(true); - 允许向连接输出数据,即允许发送POST请求的数据。
urlConn.setDoInput(true); - 允许从连接读入数据,即接收来自服务器的响应。
urlConn.setRequestMethod("POST"); - 设置请求方法为POST。
urlConn.setUseCaches(false); - 禁用缓存,确保从服务器获取最新的数据。
urlConn.setInstanceFollowRedirects(true); - 允许自动跟随重定向。
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - 设置内容类型为表单数据。这行代码用于设置HTTP请求的Content-Type头部,指明发送给服务器的数据类型。
urlConn.connect(); - 建立与服务器的实际连接
out.writeBytes(content); - 通过DataOutputStream将编码后的数据写入连接。
out.flush(); - 清空输出流,确保所有数据都被发送到服务器。
out.close(); - 关闭输出
使用DataOutputStream和其他输出流时,涉及到几个关键步骤:写入数据、刷新输出流、以及最后关闭输出流。
调用flush()方法的目的是确保所有在缓冲区中的数据都被写出到目的地中。
调用close()方法关闭输出流。关闭流是一个好习惯,可以释放与该流相关联的系统资源。