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

来源:互联网 发布:python自然语言处理 编辑:程序博客网 时间:2024/06/07 10:25
package com.http.get;


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


}


________________________________________________________________________________________________________
/**
* 获得服务器端的数据,以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()
}
}









0 0
原创粉丝点击