get,post请求

package com.main.comm.util;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.imageio.ImageIO;

public class DataConnection {
	
	public static String post(String addr, String params) throws UnsupportedEncodingException {
		  String result = "";
		  try {
		   URL url = new URL(addr);
		   URLConnection connection = url.openConnection();
		   connection.setDoOutput(true);
		   PrintWriter out = new PrintWriter(connection.getOutputStream());
		   out.write(params);
		   out.close();
		   BufferedReader in;
		   try {
			   in = new BufferedReader(new InputStreamReader(connection
						.getInputStream(),"utf-8"));
		   } catch (FileNotFoundException exception) {
		    java.io.InputStream err = ((HttpURLConnection) connection)
		      .getErrorStream();
		    if (err == null)
		     throw exception;
		    in = new BufferedReader(new InputStreamReader(err));
		   }
		   StringBuffer response = new StringBuffer();
		   String line;
		   while ((line = in.readLine()) != null)
		    response.append(line + "\n");
		   in.close();
		   
		   result = response.toString();
		  } catch (MalformedURLException e) {
		   System.err.println(e.toString());
		  } catch (IOException e) {
		   System.err.println(e.toString());
		  }
		  return result;
	}
	
	public static String get(String addr, String params) throws UnsupportedEncodingException{   
	    StringBuffer readOneLineBuff = new StringBuffer();   
	    String content ="";   
	    try {   
	        URL url = new URL(addr+"?"+params);   
	        URLConnection conn = url.openConnection();   
	        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));          
	        //InputStreamReader reader = new InputStreamReader(conn.getInputStream());
	        String line = "";   
	        while ((line = reader.readLine()) != null) {   
	            readOneLineBuff.append(line);   
	        }   
	         content = readOneLineBuff.toString();   
	        reader.close();   
	    } catch (MalformedURLException e) {   
	        e.printStackTrace();   
	    } catch (IOException e2) {   
	        e2.printStackTrace();   
	    }
	    return content;   
	}
	
	public static int getCookie(String urlString,String cookieVal,String filePath,String fileLength) throws Exception {
		HttpURLConnection httpConn = null;
		OutputStream output = null;
		InputStream reader = null;
		int contentLength = 0;
        try {  
        	if(null == fileLength || "".equals(fileLength)){
        		fileLength = "0";
        	}
            URL url = new URL(urlString);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", 
                    "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Cookie", "downloadKey="+cookieVal); // 往远程URL传递Cookie值
                
    
            OutputStream os = httpConn.getOutputStream();
            os.flush();
            os.close();
    
            int code = httpConn.getResponseCode();
            if (code == 200) { // 返回成功
            	reader = httpConn.getInputStream();
            	//查出文件大小
                contentLength = httpConn.getContentLength();
            	//如果大小相等,就不下载
                if(Integer.parseInt(fileLength) == contentLength){
                	return 0;
                }
            	File file = new File(filePath);
                if(!file.exists()){
                	file.createNewFile();//不存在则创建
                }
                output = new FileOutputStream(file);
                int finished = 0;
                // 设定读取的字节数  
                byte[] buffer = new byte[4*1024];
                int byteRead = -1;
                // 读取输入流  
                while ((byteRead=(reader.read(buffer)))!= -1) { 
                	finished = finished + byteRead;
                	output.write(buffer, 0, byteRead);
                }
                
            } else { // 访问失败
                //forward error page
                throw new Exception("Error occur when try to visit the url:" + 
                        url.getPath() + " using HttpURLConnection");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (httpConn != null)
                httpConn.disconnect();
            if(output != null){
            	output.close();
            }
            if(reader != null){
            	reader.close();
            }
        }
        return contentLength;
	}
        public static void getCookieW(String urlString,String cookieVal,String filePath) throws Exception {
    		HttpURLConnection httpConn = null;
    		BufferedWriter output = null;
    		BufferedReader reader = null;
            try {  
        
                URL url = new URL(urlString);
                httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setDoInput(true);
                httpConn.setDoOutput(true);
                httpConn.setRequestMethod("POST");
                httpConn.setRequestProperty("Content-Type", 
                        "application/x-www-form-urlencoded");     
        
                OutputStream os = httpConn.getOutputStream();
                os.flush();
                os.close();
        
                int code = httpConn.getResponseCode();
                if (code == 200) { // 返回成功
                	File file = new File(filePath);
                    if(!file.exists()){
                    	file.createNewFile();//不存在则创建
                    }
                    output = new BufferedWriter(new FileWriter(file));
                    BufferedImage image = ImageIO.read(httpConn.getInputStream());
                    ImageIO.write(image,"png",file);
                } else { // 访问失败
                    //forward error page
                    throw new Exception("Error occur when try to visit the url:" + 
                            url.getPath() + " using HttpURLConnection");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (httpConn != null)
                    httpConn.disconnect();
                if(output != null){
                	output.close();
                }
                if(reader != null){
                	reader.close();
                }
            }
    }
	

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值