标签:内部类 buffer 示例 代码 block .net package generated int
对于使用URL类请求网络服务器并接受请求进行简单处理的示例,记录下学习过程。
代码示例如下
package testHttpGet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class TestGet { public static void main(String[] args) { new ReadByGet().start(); } static class ReadByGet extends Thread{ @Override public void run() { try { //根据URL地址创建一个URL对象 URL url = new URL("https://easy-mock.com/mock/5c2f632779696b7e93ba23d6/example/testhttpget"); //获取URL连接,open方法返回一个URLConnection类的对象 URLConnection conn = url.openConnection(); //从连接获取输入流,请求的输入也就是对请求的输入,即是相应, InputStream in = conn.getInputStream(); InputStreamReader is = new InputStreamReader(in); //将字节流转换成字符流,方便操作 BufferedReader br = new BufferedReader(is); String line = null; while((line = br.readLine())!=null) { //打印相应的内容 System.out.println(line); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
结果:返回一个html页面
package testHttpGet; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class TestHttpPost { public static void main(String[] args) { new ReadByPost().start(); } static class ReadByPost extends Thread{ @Override public void run() { try { URL url = new URL("https://easy-mock.com/mock/5c2f632779696b7e93ba23d6/example/testhttpget"); //返回一个HttpURLConnection对象,他继承自URLConnection, HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置请求头 conn.addRequestProperty("encoding", "utf-8"); //设置允许对请求输入和输出参数,也就是对请求加上参数 conn.setDoInput(true); conn.setDoOutput(true); //设置请求方式为POST conn.setRequestMethod("POST"); OutputStream out = conn.getOutputStream(); OutputStreamWriter owt = new OutputStreamWriter(out); BufferedWriter bw = new BufferedWriter(owt); //对请求设置参数 bw.write("name=Tom&age=18"); //获取请求的响应,输入流 InputStream in = conn.getInputStream(); InputStreamReader is = new InputStreamReader(in); BufferedReader br = new BufferedReader(is); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
注意点:设置请求参数之前必须先设置请求方式为POST,否则会抛出异常,输入流和输出流的先后顺序也不能颠倒,因为是先请求再得到响应,所以是输出流在前,为请求设置请求参数,
输入流在后,就是得到的响应的具体内容!
标签:内部类 buffer 示例 代码 block .net package generated int
原文地址:https://www.cnblogs.com/PCBullprogrammer/p/10258178.html