Java网络编程

1.Java的基本网络支持

使用InetAddress:

package com.inetAddress;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressTest {
	public static void main(String[] args) throws IOException {
		//根据主机名来获取对应的InetAddress实例
		InetAddress ip=InetAddress.getByName("www.baidu.com");
		//判断是否可达
		System.out.println("www.baidu.com是否可达:"+ip.isReachable(2000));
		//获取该InetAddress实例的Ip字符串
		System.out.println(ip.getHostAddress());
		//根据原始Ip地质来获取对应的InetAddress实例
		InetAddress local=InetAddress.getByAddress(
				new byte[]{127,0,0,1});
		System.out.println("本机是否可达:"+local.isReachable(2000));
		//获取该InetAddress实例对应的全限定域名
		System.out.println(local.getCanonicalHostName());		
	}
}

使用URLDecoder和URLEncoder

package com.inetAddress;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/*
 * 每个中文字符占两个字节,每个字节可以转换成两个十六进制的数字
 */
public class URLDecoderTest {
	public static void main(String[] args) throws UnsupportedEncodingException {
		/*
		 * 将application/x-www-form-urlencoded字符串转换成普通字符串
		 * 其中的字符串直接从Google搜索栏复制
		 */
		String keyWord=URLDecoder.decode(
				"%E7%96%AF%E7%8B%82java%E8%AE%B2%E4%B9%89","utf-8");
		System.out.println(keyWord);
		/*
		 * 将普通字符串转换成application/x-www-form-urlencoded字符串
		 * 其中的字符串直接从Google搜索栏复制
		 */
		String urlStr=URLEncoder.encode("疯狂java讲义","utf-8");
		System.out.println(urlStr);
	}
}

2.向Web站点发送GET请求,POST请求,并从Web站点取得响应

package com.inetAddress;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class GetPostTest {
/*
 * 向指定URL发送GET方式的请求
 * @param url发送请求的URL
 * @param param 请求参数,格式满足name1=value&name2=value2的形式
 * @return URL代表远程资源的响应
 */
	public static String sendGet(String url,String param)
	{
		String result="";
		String urlName=url+"?"+param;
		try{
			URL realURl=new URL(urlName);
			//打开和URL之间的链接
			URLConnection conn=realURl.openConnection();
			//设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", 
					"Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");
			//建立实际的链接
			conn.connect();
			//获取所有的响应头字段
			Map<String,List<String>> map=conn.getHeaderFields();
			//遍历所有的响应头字段
			for(String key:map.keySet())
			{
				System.out.println(key+"--->"+map.get(key));
			}
			try(
					//定义BufferedReader输入流来读取URL的响应
					BufferedReader in=new BufferedReader(
							new InputStreamReader(conn.getInputStream(),"utf-8"))
					)
			{
				String line;
				while((line=in.readLine())!=null)
				{
					result+="\n"+line;
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("发送Get请求出现异常!"+e);
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 向指定URL发送Post请求
	 * @param url发送请求的URL
	 * @param param 请求参数,格式满足name1=value&name2=value2的形式
	 * @return URL代表远程资源的响应
	 */
	public static String sendPost(String url,String param)
	{
		String result="";
		try{
			URL realURL=new URL(url);
			//打开和URL之间的连接
			URLConnection conn=realURL.openConnection();
			//设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", 
					"Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");
			//发送post请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			try(
					//获取URLConnection对象对应的输出流
					PrintWriter out=new PrintWriter(conn.getOutputStream())
					)
			{
				//发送请求参数
				out.print(param);
				//flush输出流的缓冲
				out.flush();
			}
			try(
					//定义BufferedReader输入流来读取URL的响应
					BufferedReader in=new BufferedReader(
							new InputStreamReader(
									conn.getInputStream(),"utf-8"))
					)
			{
				String line;
				while((line=in.readLine())!=null)
				{
					result+="\n"+line;
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("发送POST请求出现异常!"+e);
			e.printStackTrace();
		}
		return result;
	}
	//提供主方法,测试发送GET和POST请求
	public static void main(String[] args) {
		//发送 GET请求
		//String s=GetPostTest.sendGet("http://localhost:8080/abc/a", null);
		//System.out.println(s);
		//发送POST请求
		String s1=GetPostTest.sendPost("http://localhost:8080/abc/login.jsp", 
				"name=crazyit.org&pass=leegang");
		System.out.println(s1);
	}
}
3多线程下载

package com.download.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class DownUtil{
	//定义下载资源的路径
	private String path;
	//指定下载的文件保存位置
	private String targetFile;
	//定义使用多少个线程下载资源
	private int threadNum;
	//定义下载的线程对象
	private DownThread[] threads;
	//定义下载的文件的总大小
	private int fileSize;
	public DownUtil(String path,String targetFile,int threadNum)
	{
		this.path=path;
		this.threadNum=threadNum;
		this.targetFile=targetFile;
		//初始化threads数组
		threads=new DownThread[threadNum];		
	}
	public void download() throws IOException
	{
		URL url=new URL(path);
		HttpURLConnection conn=(HttpURLConnection)url.openConnection();
		conn.setConnectTimeout(2000);
		conn.setRequestMethod("GET");
		conn.setRequestProperty(
				"Accept", 
				"image/gif,image/jpeg,image/pjpeg,image/pjpeg,"
				+"application/x-shockwave-flash,application/xaml+xml,"
				+"application/vnd.ms-xpsdocument,application/x-ms-xbap,"
				+"application/x-ms-application,application/vnd.ms-excel"
				+"application/vnd.ms-powerpoint,application/msword,*/*");
		conn.setRequestProperty("Accept-language", "zh—CN");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Connection", "keep-Alive");
		//得到文件大小
		fileSize=conn.getContentLength();
		conn.disconnect();
		int currentPartSize=fileSize/threadNum+1;
		RandomAccessFile file=new RandomAccessFile(targetFile,"rw");
		//设置本地文件大小
		file.setLength(fileSize);
		file.close();
		for(int i=0;i<threadNum;i++)
		{
			//计算每个线程下载的开始位置
			int startPos=i*currentPartSize;
			//每个线程使用一个RandomAccessFile进行下载
			RandomAccessFile currentPart=new RandomAccessFile(targetFile,"rw");
			//定位该线程的下载位置
			currentPart.seek(startPos);
			//创建下载线程
			threads[i]=new DownThread(startPos,currentPartSize,currentPart);
			//启动下载线程
			threads[i].start();
		}
		
	}
	//获取下载的完成百分比
	public double getCompleteRate()
	{
		//统计多个线程已经下载的总大小
		int sumSize=0;
		for(int i=0;i<threadNum;i++)
		{
			sumSize+=threads[i].length;
		}
		//返回已经完成的百分比
		return sumSize*1.0/fileSize;
	}
	private class DownThread extends Thread
	{
		//当前线程的下载位置
		private int startPos;
		//定义当前线程负责下载的大小
		private int currentPartSize;
		//当前线程需要下载的文件块
		private RandomAccessFile currentPart;
		//定义该线程已经下载的字节数
		public int length;
		public DownThread(int startPos,int currentPartSize,
		RandomAccessFile currentPart){
			this.startPos=startPos;
			this.currentPartSize=currentPartSize;
			this.currentPart=currentPart;
		}
		public void run()
		{
			try{
				URL url=new URL(path);
				HttpURLConnection conn=(HttpURLConnection)url.openConnection();
				conn.setReadTimeout(2000);
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Accept", 
						"image/gif,image/jpeg,image/pjpeg,image/pjpeg,"
								+"application/x-shockwave-flash,application/xaml+xml,"
								+"application/vnd.ms-xpsdocument,application/x-ms-xbap,"
								+"application/x-ms-application,application/vnd.ms-excel"
								+"application/vnd.ms-powerpoint,application/msword,*/*");
				conn.setRequestProperty("Accept-Language", "zh-CN");
				conn.setRequestProperty("Charset", "UTF-8");
				InputStream intStream=conn.getInputStream();
				//跳过startPos字节,表明该线程只下载自己负责的那部分文件
				intStream.skip(this.startPos);
				byte[] buffer=new byte[1024];
				int hasRead=0;
				//读取网络数据,并写入本地文件
				while(length<currentPartSize&&(hasRead=intStream.read(buffer))!=-1)
						{
							currentPart.write(buffer,0,hasRead);
							//累计该线程下载的总大小
							length+=hasRead;
						}
					currentPart.close();
					intStream.close();
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
	}
}
package com.download.test;
import java.io.IOException;
public class MutiThreadDown {
	public static void main(String[] args) throws IOException {
		//初始化DownUtil对象
		final DownUtil downUtil=new DownUtil("http://b.hiphotos.baidu.com/"+
		"image/pic/item/2cf5e0fe9925bc3165ef6b965cdf8db1cb137009.jpg","ios.png",2);
		//开始下载
		downUtil.download();
		new Thread(()->{
		while(downUtil.getCompleteRate()<1)
		{
			//每隔0.1秒查询一次任务的完成进度
			//GUI程序中可根据该进度来绘制进度条
			System.out.println("已完成:"+
			downUtil.getCompleteRate());
			try{
				Thread.sleep(1000);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		}).start();
	}
}

4.使用Socket进行通信

package com.socket.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket socket=new Socket("127.0.0.1",3000);
		//将socket对应的输入流包装成BufferedReader
		BufferedReader br=new BufferedReader(
				new InputStreamReader(socket.getInputStream()));
		//进行普通IO操作
		String line=br.readLine();
		System.out.println("来自服务器的数据:"+line);
		//关闭输入流,关闭socket
		br.close();
		socket.close();
	}
}
package com.socket.test;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
	public static void main(String[] args) throws IOException {
		//创建一个serversocket,用于监听客户端socket请求
		ServerSocket ss=new ServerSocket(3000);
		//采用循环不断接受来自客户端的请求
		while(true)
		{
			//每当接收到客户端socket的请求时,服务器端也对应产生一个socket
			Socket s=ss.accept();
			//将socket对应的输出流包装成printStream
			PrintStream ps=new PrintStream(s.getOutputStream());
			//进行普通IO操作
			ps.println("您好!您收到了来自服务器的响应!");
			//关闭输出流,关闭socket
			ps.close();
			s.close();
		}
	}
}






















































  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值