图片工具类

图片上传

package com.testutil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
 * 但不够简便;
 * 
 * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
 * 4.以输入流的形式获取返回内容 5.关闭输入流
 * 
 * @author H__D
 *  影像上传接口(外挂)
 */
public class ImageUploadTestByWg {


    /**
     * 多文件上传的方法
     * 
     * @param actionUrl:上传的路径
     * @param uploadFilePaths:需要上传的文件路径,数组
     * @return
     */
    @SuppressWarnings("finally")
    public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        DataOutputStream ds = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            // 设置DataOutputStream
            ds = new DataOutputStream(httpURLConnection.getOutputStream());
            for (int i = 0; i < uploadFilePaths.length; i++) {
                String uploadFile = uploadFilePaths[i];
                String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
                ds.writeBytes(twoHyphens + boundary + end);
                ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
                        + "\"" + end);
                ds.writeBytes(end);
                FileInputStream fStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                while ((length = fStream.read(buffer)) != -1) {
                    ds.write(buffer, 0, length);
                }
                ds.writeBytes(end);
                fStream.close();
            }
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            ds.flush();
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                try {
                    ds.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultBuffer.toString();
        }
    }

    public static void main(String[] args) {
        // 上传文件测试
         String str = uploadFile("http://10.0.100.17:6013/ImageExt/uploadImage?app_code =GIS_C_11",
        		 new String[] { "e://129900749.zip" });
         System.out.println(str);
    }
}

图片下载

package com.testutil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
 * 影像下载
 * @author zhaozj
 *
 */
public class ImageDownLoadTest {
	/**
	 * 影像列表参数下载
	 * @throws Exception
	 */
	public void test2() throws Exception {
		//上传
		//String str = uploadFile("http://10.0.100.17:6013/ImageExt/uploadImage?app_code =GIS_C_11",
		
		//影像列表参数下载
		String urlStr = "http://10.0.100.17:6013/ImageExt/getImageList?app_code=GIS_C_11&busi_no=07I1010200111102018000002";
		GetMethod getMethod = new GetMethod(urlStr);
		getMethod.getParams().setContentCharset("utf-8");
		HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				"utf-8");
		client.getHttpConnectionManager().getParams().setConnectionTimeout(
				50000);
		int statusCode = client.executeMethod(getMethod);
		if (statusCode != HttpStatus.SC_OK) {
			System.out.println(getMethod.getStatusLine());
			throw new IllegalStateException("Method failed: "
					+ getMethod.getStatusLine());
		}
		InputStream inputStream = getMethod.getResponseBodyAsStream();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream, "UTF-8"));
		String strMessage = null;
		StringBuffer buffer = new StringBuffer();
		while ((strMessage = reader.readLine()) != null) {
			buffer.append(strMessage);
		}
		System.out.println(buffer.toString());
		getMethod.releaseConnection();
	}

	/**
	 * 影像图片下载
	 * @throws Exception
	 */
	public void test3() throws Exception {
		//影像图片下载
		String urlStr = "http://10.0.100.17:6013/ImageExt/viewImage?path=/TRMTP/GIS_C_11/2018/03/09/78/74/62fd395f17bf3297a5a57e74774dc121_1/6fb934ba-a8b0-4f8f-9968-85be6ee296f6.jpg";
		GetMethod getMethod = new GetMethod(urlStr);
		getMethod.getParams().setContentCharset("utf-8");
		HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				"utf-8");
		client.getHttpConnectionManager().getParams().setConnectionTimeout(
				50000);
		int statusCode = client.executeMethod(getMethod);
		if (statusCode != HttpStatus.SC_OK) {
			System.out.println(getMethod.getStatusLine());
			throw new IllegalStateException("Method failed: "
					+ getMethod.getStatusLine());
		}
		InputStream inputStream = getMethod.getResponseBodyAsStream();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream, "UTF-8"));
		String strMessage = null;
		StringBuffer buffer = new StringBuffer();
		while ((strMessage = reader.readLine()) != null) {
			buffer.append(strMessage);
		}
		System.out.println(buffer.toString());
		getMethod.releaseConnection();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值