java學習第二階段day6


URL 和 HttpClient 從服務器下載數據(GET) 或 上傳數據方式(POST)java

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;apache

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 postpost


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 postui

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();
  }
 }
}url

相關文章
相關標籤/搜索