java学习第二阶段day6


URL 和 HttpClient 从服务器下载数据(GET) 或 上传数据方式(POST)

package com.homwork12_29;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class DownLoadMethod {
 public static byte[] urlmethod(String path){
  try {
   //创建一个URL对象
   URL url = new URL(path);
   //打开连接
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   //设置请求 为 get(从服务器拿数据)
   connection.setRequestMethod("GET");
   //开始连接
   connection.connect();
   //取得服务器 的响应
   int code = connection.getResponseCode();
   //判断服务器响应是否成功
   if(code == 200){
    InputStream is = connection.getInputStream();
    //内存流 把要从服务器下载的数据写到内存中
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int length = 0;
    while((length = is.read(b)) != -1){
     bos.write(b,0,length);
    }
    //从内存中去出数据(字节型)返回给用户
    return bos.toByteArray();
   }
   
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
 public static byte[] clientmethod(String path){
  //创建一个httpclient对象
  HttpClient client = new DefaultHttpClient();
  //创建一个请求
  HttpGet get = new HttpGet(path);
  //执行请求  并返回一个HttpResponse 对象
  HttpResponse response;
  try {
   response = client.execute(get);
   int code = response.getStatusLine().getStatusCode();
   //判断服务器是否 响应
   if(code == 200){
    //从服务器 拿下载的数据
    HttpEntity entity = response.getEntity();
    //把从服务器拿到的数据转换成字节 返回
    byte[] b = EntityUtils.toByteArray(entity);
    return b;
   }
  } catch (ClientProtocolException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  return null; 
 }
 //保存 数据到 指定的文件夹 的方法
 public static void savapath(String path ,String decpath){
  byte[] b = urlmethod(path);
  if(b != null){
   try {
    //文件名字
    String file_name = path.substring(path.lastIndexOf('/')+1);
    File file = new File(decpath);
    file.mkdirs();
    //写入数据到指定的文件夹
    OutputStream os = new FileOutputStream(decpath + "\\"+ file_name);
    os.write(b);
    os.close();
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}
-----------
Test

import java.util.Scanner;
public class Test1 {
 public static void main(String[] args) {
  DownLoadMethod download = new DownLoadMethod();
  System.out.println("[1] url方法下载\r\n[2] client方法下载\r\n[0] 退出");
  System.out.println("请选择下载方式:");
  Scanner sc = new Scanner(System.in);
  while(true){
  int choose = sc.nextInt();
  if(choose == 1 || choose == 2 || choose == 0){
  switch(choose){
  case 1:     System.out.println("请输入下载地址:");
              String url_name = sc.next();
              System.out.println("请输入保存路径:");
              String sava_path1 = sc.next();
              download.urlmethod(url_name);
              download.savapath(url_name, sava_path1);
              break;
  case 2:     System.out.println("请输入下载地址:");
                    String client_name = sc.next();
                    System.out.println("请输入保存路径:");
                    String sava_path2 = sc.next();
                   download.clientmethod(client_name);
                   download.savapath(client_name, sava_path2);
                   break;
  default:  System.exit(0);
  }
  }else{
   System.out.println("输入错误,请重新输入0-2的选项!");
  }
  }
 }
}
-------------------------------------------------------------------------
URL post


public class WriterServlet {
 public static void main(String[] args) throws Exception  {
  String path = "http://127.0.0.1:8080/Login/login";
  URL url = new URL(path);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod("POST");
  connection.setDoOutput(true);
  OutputStream os = connection.getOutputStream();
//  connection.connect();
  os.write("name=admin&pwd=110".getBytes());
  int code = connection.getResponseCode();
  byte[] b = new byte[1024];
  int length = 0;
  if(code == 200){
   InputStream is = connection.getInputStream();
   length = is.read(b);
   System.out.println(new String(b,0,length));
  }
 }
}
---------------------------------------------------------------------
HttpClient post

public class HttpClientPost {
 public static void main(String[] args) {
  //需要导入阿帕奇第三方 包 然后右键 在build path 配置路径
  //创建一个HttpClient 对象
  HttpClient client = new DefaultHttpClient();
  String path = "";
  //创建一个请求
  HttpPost post = new HttpPost(path);
  NameValuePair parameters1 = new BasicNameValuePair("username", "admin");
  NameValuePair parameters2 = new BasicNameValuePair("userpwd","123");
  List<NameValuePair> list = new ArrayList<NameValuePair>();
  list.add(parameters1);
  list.add(parameters2);
  HttpEntity entity;
  try {
   entity = new UrlEncodedFormEntity(list);
   post.setEntity(entity);
   HttpResponse response = client.execute(post);
   int code = response.getStatusLine().getStatusCode();
   if(code == 200){
    HttpEntity entity2 = response.getEntity();
    String str = EntityUtils.toString(entity2);
    System.out.println(str);
   }
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


 

转载于:https://my.oschina.net/u/2542711/blog/595727

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值