基于HTTP的客户端与服务器交互编程

基于java实现的客户端与服务器交互编程

    

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


class MyHttpUtils 
{

/*
  要访问一个服务器图片的资源完整路径,首先Pro1.png是放在服务器端的myhttp目录下的
  整个路径包含和协议+IP/Port+服务器端的工程名和资源名
*/
private static String URLPATH="http://192.168.0.102:8080/myhttp/pro1.png";
public MyHttpUtils()
{
} 


/*下面要写一个通用的方法,目的是把从服务器拿到的资源写到本地的磁盘*/
public static void saveImageToDesk(){

InputStream inputStream = getInputStream();
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try{

fileOutputStream = new FileOutputStream("C:\\test.png");//在这里因为是本地路径,所以反斜线要进行转义
while((len=inputStream.read(data)!=-1)){
fileOutputStream.write(data,0,len);
}
}catch(IOException e){

e.printStackTrace();

}finally{

if(inputStream!=null){
  try{
inputStream.close();
}catch(IOException e)
{
 e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
   }//catch
  }//if
 }while
}//main
_____________________________________________________________________________________________________
/**
* 获得服务器端的数据,以InputStream形式返回
* @return
*/
public static InputStream getInputStream(){
//创建一个输入流对象
InputStream inputStream = null;
//创建HttpURLConnection类的对象,用来处理客户端和服务器进行数据交换的工作
HttpURLConnection httpURLConnection = null;
   try{
    //因为这个类是用来处理客户端和服务器交流的,整个代码是客户端代码,所以要给一个服务器端的路径
      URL url = new URL(URLPATH);
     if(url!=null){
      /*url用传进来的路径与服务器建立好连接,并在openConnection方法中对httpURLConnection进行一些
      基本的参数设置,这样就拿到与服务器建立好连接的对象(这个时候拿到的httpURLConnection对象只是最
      基本的只与服务器建立好连接的对象,接下来还要对参数进行设置)*/
      httpURLConnection = (HttpURLConnection)url.openConnection();
     //设置网络连接超时的时间
      httpURLConnection.setConnectTimeout(3000);
    //设置是否接受输入
    httpURLConnection.setDoInput(true);
    // 表示设置本次http请求使用GET方式请求
    httpURLConnection.setRequestMethod("GET");
  /*getResponseCode这个方法一定包含了把httpURLConnection设置的参数发送给服务器,
  并拿到服务器返回的表示的码,然后进行一个return*/
   int responseCode = httpURLConnection.getResponseCode();
   if (responseCode == 200) {
   /* 从服务器获得一个输入流,其实这个输入流就是httpURLConnection通过getInputStream()方法
  把从服务器端拿回来的数据封装在InputStream对象中,再return*/
  inputStream = httpURLConnection.getInputStream();
  }
   }
    }catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
 }
}
______________________________________________________________________


public static void main(String[] args) 
{
saveImageToDesk()
}
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值