HttpUrlConnection编程

来源:互联网 发布:藏刀不能在淘宝卖 编辑:程序博客网 时间:2024/05/01 13:10


          http编程(重点)
          http:超文本传输协议
          xml,json
          HttpUrlConnection
          HttpClient
3、HttpUTLconnection使用步骤
      a:首先确定资源的地址
      b:根据地址封装成URL对象
             URL:uniform Resource Locator,统一资源定位符
      c:创建程序与资源的连接
      d:设置请求方式,get,post
      e:设置输入,输出操作
      f:打开连接
      g:根据返回的状态码(200表示成功),进行读写操作


                      // 资源地址
案例一:       String path = "http://10.9.153.74:8080/Day28/ab.jpg";
// 封装成URL对象
URL url = new URL(path);
// 创建程序与资源的连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 设置请求方式
urlConn.setRequestMethod("GET");
// 设置输入操作
urlConn.setDoInput(true);
// 打开连接
urlConn.connect();
// 判断状态码,如果为200,表示访问成功,可以使用流进行读写操作
if (urlConn.getResponseCode() == 200) {
InputStream is = urlConn.getInputStream();
FileOutputStream fos = new FileOutputStream("c:/1.png");
byte[] b = new byte[1024];
int n = 0;
while ((n = is.read(b)) != -1) {
fos.write(b, 0, n);
}
fos.close();
System.out.println("下载成功!");
}
案例二:       //下载图片,先将图片写入内存,之后将内存中的数据写入本地文件       注:如果是汉字,要注意乱码问题
                  String path = "http://10.9.153.74:8080/Day28/ab.jpg";
  try {
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
urlConn.connect();
if (urlConn.getResponseCode() == 200) {
InputStream is = urlConn.getInputStream();
// 写入内存
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n = 0;
while ((n = is.read(b)) != -1) {
baos.write(b, 0, n);
baos.flush();
}


// 写入本地文件
FileOutputStream fos = new FileOutputStream("c:/a.jpg");
fos.write(baos.toByteArray());
fos.close();
}
 案例三:登录验证,获得服务器返回信息    //提交方式是get
         String path = "http://10.9.153.194:8080/day27/" + "LoginServlet?username=admin&password=123456";
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
urlConn.connect();
if (urlConn.getResponseCode() == 200) {
InputStream is = urlConn.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
System.out.println(br.readLine());
br.close();
}


 案例四:登录验证,将用户名和密码上传到服务器   //当提交方式是post
String path = "http://10.9.153.194:8080/day27/LoginServlet";
String param = "username=admin&password=123456";
try {
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();


// 设置请求方式
urlConn.setRequestMethod("POST");
// 设置输入输出操作
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.connect();


// 获得输出流,向服务器发送数据
OutputStream os = urlConn.getOutputStream();
os.write(param.getBytes());


if (urlConn.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
         System.out.println(new String(br.readLine().getBytes(), "utf-8"));
                        }






     
0 0