`

Http协议编程

阅读更多

     今天学习了Http协议编程,以前听过一些,今天又拓宽了一下。

     首先,有两种方式:

      1.java 接口

      2.apache接口

     先来演示下java 接口编程:

     (1)通过http,get请求从服务器取得数据

     

public class Java_Get {
   public static String URL_PATH ="http://192.168.1.104:8080/MyHttp/logo1.jpg" ;
   /**
    * 获得服务器端的数据以输入流返回
    * @return
    */
	public static InputStream getInputStream(){
		
		InputStream inputStream = null ;
		try {
			//创建URL对象
			URL url = new URL(URL_PATH);
			if(url!=null){
			//取得HttpsURLConnection连接对象
			HttpURLConnection httpURLConnection =	(HttpURLConnection) url.openConnection() ;
			//设置连接网络超时时间,超过3秒自动断开
			httpURLConnection.setConnectTimeout(3000) ;
			//将 doInput 标志设置为 true,指示应用程序要从 URL 连接读取数据。 
			httpURLConnection.setDoInput(true) ;
			//将 doOutput 标志设置为 true,指示应用程序要将数据写入 URL 连接。 
			httpURLConnection.setRequestMethod("GET") ;
			int responseCode = httpURLConnection.getResponseCode() ;
			//判断是否正常返回数据
			if(responseCode == HttpURLConnection.HTTP_OK){
				//从服务器获得输入流
				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  saveImage(){
		InputStream inputStream = getInputStream()  ;
		byte[] data = new byte[1024] ;
		FileOutputStream fileOutputStream =  null ;
		int len = 0 ;
		//图片小于1024个字节
		try {
			fileOutputStream = new FileOutputStream("D:\\ee.jpg") ;
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data,0,len) ;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(inputStream!=null){
				try {
					inputStream.close() ;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(fileOutputStream!=null){
				try {
					fileOutputStream.close() ;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		//从服务器获取图片保存到本地
		saveImage() ;
	}
}

     (2)通过http,post从服务器取得数据

  

public class Java_Post {
	private static String URL_PATH = "http://192.168.1.104:8080/MyHttp/LoginServlet";
	private static URL url;
	// 静态块实例化
	static {
		try {
			url = new URL(URL_PATH);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param params
	 *            填入url的参数
	 * @param encode
	 *            字节编码
	 * @return
	 */
	public static String sendPostMessage(Map<String, String> params,
			String encode) {
		StringBuffer stringBuffer = new StringBuffer();
		if (params != null && !params.isEmpty()) {
			try {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					stringBuffer
							.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), encode))
							.append("&");
				}
			stringBuffer.deleteCharAt(stringBuffer.length()-1) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setConnectTimeout(3000) ;
			urlConnection.setDoInput(true) ;
			urlConnection.setDoOutput(true) ;
			//获得上传信息的字节大小以及长度
			byte[] data = stringBuffer.toString().getBytes() ;
			//设置请求的类型为文本类型
			urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") ;
			urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length)) ;
		    OutputStream outputStream = urlConnection.getOutputStream() ;
		    outputStream.write(data) ;
		    int responseCode = urlConnection.getResponseCode() ;
		    if(responseCode == HttpURLConnection.HTTP_OK){
		    return changeInputStream(urlConnection.getInputStream(),encode) ;
		    }
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
      
		return "";
	}
        /**
        * 将读到的流转化为字符串
        * @param inputStream
        * @param encode
        * @return
        */
	private static String changeInputStream(InputStream inputStream,String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream() ;
		byte[] data = new byte[1024] ;
		int len = 0 ;
		String result = "" ;
		try {
			if(inputStream!=null){
				while((len = inputStream.read(data))!=-1){
					outputStream.write(data, 0, len) ;
				}
				result = new String(outputStream.toByteArray(),encode) ;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static void main(String[] args) {
          Map<String,String> map = new HashMap<String,String>() ;
          map.put("username", "再_见孙悟空") ;
          map.put("userpwd", "AMB") ;
         String text = sendPostMessage(map,"utf-8");
         System.out.println(text); 
	}
}

  

 

 

 2.apache ,post从服务器取得数据

  

public class Apache_Http {
    /**
     * 取得从服务器返回信息
     * @param path : 地址
     * @param map : 传递的信息
     * @param encode : 编码
     * @return
     */
	public static String sendHttpPost(String path, Map<String,String> map,
			String encode) {
        List<NameValuePair> list = new ArrayList<NameValuePair>() ;
        if(map!=null && !map.isEmpty()){
        	for(Map.Entry<String,String> entry : map.entrySet())
        	list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())) ;
        }
        //将请求的参数封装到表单中
        try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode) ;
		   HttpPost httpPost = new HttpPost(path) ;
		   httpPost.setEntity(entity) ;
		   DefaultHttpClient client = new DefaultHttpClient() ;
		   HttpResponse httpResponse = client.execute(httpPost) ;
		   if(httpResponse.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK){
			 return changeInputStream( httpResponse.getEntity().getContent() ,encode);//得到输入流
		   }
        } 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();
		}
		return "" ;
	}
	/**
	 * 将读到的流转化为字符串
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	private static String changeInputStream(InputStream inputStream,String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream() ;
		byte[] data = new byte[1024] ;
		int len = 0 ;
		String result = "" ;
		try {
			if(inputStream!=null){
				while((len = inputStream.read(data))!=-1){
					outputStream.write(data, 0, len) ;
				}
				result = new String(outputStream.toByteArray(),encode) ;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	public static void main(String[] args) {
		String URL_PATH = "http://192.168.1.104:8080/MyHttp/LoginServlet";
		Map<String,String> map = new HashMap<String,String>() ;
        map.put("username", "再_见孙悟空") ;
        map.put("userpwd", "AMB") ;
       String text = sendHttpPost(URL_PATH,map,"utf-8");
       System.out.println(text);
	}
}

 


 

  • 大小: 15 KB
  • 大小: 3.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics