精华内容
下载资源
问答
  • java实现get类型接口调用

    千次阅读 2020-02-18 20:18:02
    GET: (一)GET通常用于获取服务端数据。 常见发起GET请求的方式有:URL 、src/href、表单(form)。 (二)GET方式提交数据的格式: 格式:index.php?userName=jack&password=123 (注意:index....

    GET:

    		(一)GET通常用于获取服务端数据。
    		常见发起GET请求的方式有:URL 、src/href、表单(form)。
    		(二)GET方式提交数据的格式:
    		格式:index.php?userName=jack&password=123 (注意:index.php?key=value&key=value。 userName=jack&password=123 叫做查询字符串)
    		参数名与参数值之间没有空格
    		参数值不需要使用单双引号包括
    		(三)GET方式提交数据特点:
    		1、get方式在url后面拼接参数,只能以文本的形式传递参数。
    		2、传递的数据量小,4kb左右(不同浏览器会有差异)。
    		3、安全性低,会将信息显示在地址栏。
    		4、速度快,通常用于对安全性要求不高的请求
    

    (四)用java实现简单的get请求。

    /**
    	 * 无参数的get请求
    	 * 
    	 * @param uri 接口地址
    	 */
    	public static String doGet(String uri) {
    		try {
    //		 * 1、创建request连接.
    			HttpGet get = new HttpGet(uri);
    			// 设置请求头
    			get.setHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
    			// 创建一个客户端
    			HttpClient client = HttpClients.createDefault();
    			// 发送请求,并接受响应
    			HttpResponse response = client.execute(get);
    			// 获取接口响应封装到一个方法中,方便调用,返回body
    			return getResult(response);
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 带参数的get请求,参数为map
    	 * 
    	 * @param uri 接口地址
    	 * @param map 接口参数
    	 */
    	public static String doGet(String uri, Map<String, String> mapParams) {
    		try {
    			// 在uri上拼接参数2.那么一个完整的url地址,基本格式如下:
    			// https://host:port/path?xxx=aaa&ooo=bbb
    			Set<String> keySet = mapParams.keySet();
    			int i = 0;
    			for (String key : keySet) {
    				if (i == 0) {
    					uri = uri + "?" + key + "=" + mapParams.get(key);
    				} else {
    					uri = uri + "&" + key + "=" + mapParams.get(key);
    				}
    				i++;
    			}
    			// 创建一个get请求
    			HttpGet get = new HttpGet(uri);
    			// 设置请求头
    			get.addHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
    			get.addHeader(Constants.CONTENT_TYPE, Constants.CONTENT_TYPE_FORM);
    			// 创建一个客户端
    			HttpClient client = HttpClients.createDefault();
    			// 客户端发送请求,接受响应
    			HttpResponse response = client.execute(get);
    			return getResult(response);
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    	/**
    	 * 获取响应结果
    	 * 
    	 * @param response
    	 * @return
    	 * @throws IOException
    	 */
    	public static String getResult(HttpResponse response) throws IOException {
    		// 获取状态码
    		int code = response.getStatusLine().getStatusCode();
    		System.out.println(code);
    		// 获取body
    		HttpEntity entity = response.getEntity();
    		String body = EntityUtils.toString(entity);
    		System.out.println(body);
    		// 获取头信息
    		Header[] allHeaders = response.getAllHeaders();
    		String headers = Arrays.toString(allHeaders);
    		System.out.println(headers);
    
    		// 返回body
    		return body;
    	}
    
    展开全文
  • java实现 get、put、post、delete请求

    千次阅读 2016-12-28 16:19:19
    java"] public static String doGet(String strUrl ){ String strReturn=""; HttpGet httpGet = new HttpGet(strUrl); CloseableHttpClient httpclient = null; Closeable...
    1、get

    public static String doGet(String strUrl ){
    String strReturn="";
    HttpGet httpGet = new HttpGet(strUrl);
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response1=null;
    try {
    httpclient = HttpClients.createDefault();
    response1 = httpclient.execute(httpGet);
    HttpEntity entity1 = response1.getEntity();
    strReturn=EntityUtils.toString(entity1) ;
    EntityUtils.consume(entity1);
    }catch(Exception e){
    e.printStackTrace();
    }finally {
    try {
    if(response1!=null)
    response1.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return strReturn;
    }

    2、put

    public static String doPut(String strUrl,String param){
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String strReturn="";
    PutMethod httpput=new PutMethod(strUrl);
    try {
    if(param!=null)
    {
    RequestEntity entity = new StringRequestEntity(param, "application/json", "UTF-8");
    httpput.setRequestEntity(entity);
    }
    httpClient.executeMethod(httpput);
    byte[] bytes = httpput.getResponseBody();
    strReturn= new String(bytes) ;
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return strReturn;
    }

    3、post

    public static String doPost(String requestUrl, String payload) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String strReturn="";
    PostMethod httpost = new PostMethod(requestUrl);
    try {
    if(payload!=null)
    {
    RequestEntity entity = new StringRequestEntity(payload, "application/json", "UTF-8");
    httpost.setRequestEntity(entity);
    }
    httpClient.executeMethod(httpost);
    byte[] bytes = httpost.getResponseBody();
    strReturn= new String(bytes) ;
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return strReturn;
    }

    4、delete

    public static void doDelete(String urlToRead) throws Exception {
    URL url = new URL(urlToRead);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestProperty(
    "Content-Type", "application/x-www-form-urlencoded" );
    httpCon.setRequestMethod("DELETE");
    httpCon.connect();
    httpCon.disconnect();

    }
    展开全文
  • JAVAGET和POST请求实现方式

    万次阅读 多人点赞 2018-03-15 16:41:30
    一、介绍使用Java实现GET和POST请求的方法常用的有两种:HTTPClient和HttpURLConnection。前者是第三方开源框架实现,对HTTP请求的封装很好,使用HTTPClient基本可以满足工作需要,其中HTTPClient3.1是org.apache....

    一、介绍

    使用Java实现GET和POST请求的方法常用的有两种:HTTPClient和HttpURLConnection。前者是第三方开源框架实现,对HTTP请求的封装很好,使用HTTPClient基本可以满足工作需要,其中HTTPClient3.1是org.apache.commons.httpclient下操作远程url的工具包,HTTPClient4.5.5是org.apache.http.client下操作远程url的工具包。而HttpURLConnection是java的标准请求方式。

    二、实现

    1.HttpURLConnection原生实现方式:

    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class HttpClient {
        public static String doGet(String httpurl) {
            HttpURLConnection connection = null;
            InputStream is = null;
            BufferedReader br = null;
            String result = null;// 返回结果字符串
            try {
                // 创建远程url连接对象
                URL url = new URL(httpurl);
                // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
                connection = (HttpURLConnection) url.openConnection();
                // 设置连接方式:get
                connection.setRequestMethod("GET");
                // 设置连接主机服务器的超时时间:15000毫秒
                connection.setConnectTimeout(15000);
                // 设置读取远程返回的数据时间:60000毫秒
                connection.setReadTimeout(60000);
                // 发送请求
                connection.connect();
                // 通过connection连接,获取输入流
                if (connection.getResponseCode() == 200) {
                    is = connection.getInputStream();
                    // 封装输入流is,并指定字符集
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    // 存放数据
                    StringBuffer sbf = new StringBuffer();
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("\r\n");
                    }
                    result = sbf.toString();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                connection.disconnect();// 关闭远程连接
            }
    
            return result;
        }
    
        public static String doPost(String httpUrl, String param) {
    
            HttpURLConnection connection = null;
            InputStream is = null;
            OutputStream os = null;
            BufferedReader br = null;
            String result = null;
            try {
                URL url = new URL(httpUrl);
                // 通过远程url连接对象打开连接
                connection = (HttpURLConnection) url.openConnection();
                // 设置连接请求方式
                connection.setRequestMethod("POST");
                // 设置连接主机服务器超时时间:15000毫秒
                connection.setConnectTimeout(15000);
                // 设置读取主机服务器返回数据超时时间:60000毫秒
                connection.setReadTimeout(60000);
    
                // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
                connection.setDoOutput(true);
                // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
                connection.setDoInput(true);
                // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
                connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                // 通过连接对象获取一个输出流
                os = connection.getOutputStream();
                // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
                os.write(param.getBytes());
                // 通过连接对象获取一个输入流,向远程读取
                if (connection.getResponseCode() == 200) {
    
                    is = connection.getInputStream();
                    // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                    StringBuffer sbf = new StringBuffer();
                    String temp = null;
                    // 循环遍历一行一行读取数据
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("\r\n");
                    }
                    result = sbf.toString();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 断开与远程地址url的连接
                connection.disconnect();
            }
            return result;
        }
    }

    2.java原生HttpClient3.1

    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    public class HttpClient3 {
    
        public static String doGet(String url) {
            // 输入流
            InputStream is = null;
            BufferedReader br = null;
            String result = null;
            // 创建httpClient实例
            HttpClient httpClient = new HttpClient();
            // 设置http连接主机服务超时时间:15000毫秒
            // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建一个Get方法实例对象
            GetMethod getMethod = new GetMethod(url);
            // 设置get请求超时为60000毫秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
            try {
                // 执行Get方法
                int statusCode = httpClient.executeMethod(getMethod);
                // 判断返回码
                if (statusCode != HttpStatus.SC_OK) {
                    // 如果状态码返回的不是ok,说明失败了,打印错误信息
                    System.err.println("Method faild: " + getMethod.getStatusLine());
                } else {
                    // 通过getMethod实例,获取远程的一个输入流
                    is = getMethod.getResponseBodyAsStream();
                    // 包装输入流
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                    StringBuffer sbf = new StringBuffer();
                    // 读取封装的输入流
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp).append("\r\n");
                    }
    
                    result = sbf.toString();
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 释放连接
                getMethod.releaseConnection();
            }
            return result;
        }
    
        public static String doPost(String url, Map<String, Object> paramMap) {
            // 获取输入流
            InputStream is = null;
            BufferedReader br = null;
            String result = null;
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建post请求方法实例对象
            PostMethod postMethod = new PostMethod(url);
            // 设置post请求超时时间
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    
            NameValuePair[] nvp = null;
            // 判断参数map集合paramMap是否为空
            if (null != paramMap && paramMap.size() > 0) {// 不为空
                // 创建键值参数对象数组,大小为参数的个数
                nvp = new NameValuePair[paramMap.size()];
                // 循环遍历参数集合map
                Set<Entry<String, Object>> entrySet = paramMap.entrySet();
                // 获取迭代器
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
    
                int index = 0;
                while (iterator.hasNext()) {
                    Entry<String, Object> mapEntry = iterator.next();
                    // 从mapEntry中获取key和value创建键值对象存放到数组中
                    try {
                        nvp[index] = new NameValuePair(mapEntry.getKey(),
                                new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    index++;
                }
            }
            // 判断nvp数组是否为空
            if (null != nvp && nvp.length > 0) {
                // 将参数存放到requestBody对象中
                postMethod.setRequestBody(nvp);
            }
            // 执行POST方法
            try {
                int statusCode = httpClient.executeMethod(postMethod);
                // 判断是否成功
                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method faild: " + postMethod.getStatusLine());
                }
                // 获取远程返回的数据
                is = postMethod.getResponseBodyAsStream();
                // 封装输入流
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp).append("\r\n");
                }
    
                result = sbf.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 释放连接
                postMethod.releaseConnection();
            }
            return result;
        }
    }

    3.java原生httpClient4.5

    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    public class HttpClient4 {
    
        public static String doGet(String url) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            String result = "";
            try {
                // 通过址默认配置创建一个httpClient实例
                httpClient = HttpClients.createDefault();
                // 创建httpGet远程连接实例
                HttpGet httpGet = new HttpGet(url);
                // 设置请求头信息,鉴权
                httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                // 设置配置请求参数
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                        .setConnectionRequestTimeout(35000)// 请求超时时间
                        .setSocketTimeout(60000)// 数据读取超时时间
                        .build();
                // 为httpGet实例设置配置
                httpGet.setConfig(requestConfig);
                // 执行get请求得到返回对象
                response = httpClient.execute(httpGet);
                // 通过返回对象获取返回数据
                HttpEntity entity = response.getEntity();
                // 通过EntityUtils中的toString方法将结果转换为字符串
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != response) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
    
        public static String doPost(String url, Map<String, Object> paramMap) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse httpResponse = null;
            String result = "";
            // 创建httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                    .setSocketTimeout(60000)// 设置读取数据连接超时时间
                    .build();
            // 为httpPost实例设置配置
            httpPost.setConfig(requestConfig);
            // 设置请求头
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // 封装post请求参数
            if (null != paramMap && paramMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                // 通过map集成entrySet方法获取entity
                Set<Entry<String, Object>> entrySet = paramMap.entrySet();
                // 循环遍历,获取迭代器
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> mapEntry = iterator.next();
                    nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
    
                // 为httpPost设置封装好的请求参数
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            try {
                // httpClient对象执行post请求,并返回响应参数对象
                httpResponse = httpClient.execute(httpPost);
                // 从响应对象中获取响应内容
                HttpEntity entity = httpResponse.getEntity();
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != httpResponse) {
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
    }
    传入的参数是json或者其他格式需要更改请求头及参数的设置信息,httpPost.setEntity(new StringEntity("你的json串"));      httpPost.addHeader("Content-Type", "application/json")。
    展开全文
  • java实现在线预览--poi实现word、excel、ppt转html

    万次阅读 多人点赞 2019-07-31 18:39:43
    java实现在线预览- -之poi实现word、excel、ppt转html

    java实现在线预览

    - -之poi实现word、excel、ppt转html

    ###简介
    java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office、office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0
    如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行,可参考这篇文章http://blog.csdn.net/z69183787/article/details/17468039,写的挺细的,实现原理就是:
    1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件;
    2.通过swfTools将pdf文件转换成swf格式的文件;
    3.通过FlexPaper文档组件在页面上进行展示。
    当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。
    我这里介绍通过poi实现word、excel、ppt转html,这样就可以放在页面上了。

    ###word转html

    package wordToHtml;
    
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.apache.commons.io.FileUtils;
    import org.apache.poi.hwpf.HWPFDocument;
    import org.apache.poi.hwpf.converter.PicturesManager;
    import org.apache.poi.hwpf.converter.WordToHtmlConverter;
    import org.apache.poi.hwpf.usermodel.Picture;
    import org.apache.poi.hwpf.usermodel.PictureType;
    import org.w3c.dom.Document;
    public class PoiWordToHtml {
     public static void main(String[] args) throws Throwable {
      final String path = "D:\\poi-test\\wordToHtml\\";
      final String file = "人员选择系分.doc";
      InputStream input = new FileInputStream(path + file);
      HWPFDocument wordDocument = new HWPFDocument(input);
      WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
        DocumentBuilderFactory.newInstance().newDocumentBuilder()
          .newDocument());
      wordToHtmlConverter.setPicturesManager(new PicturesManager() {
       public String savePicture(byte[] content, PictureType pictureType,
         String suggestedName, float widthInches, float heightInches) {
        return suggestedName;
       }
      });
      wordToHtmlConverter.processDocument(wordDocument);
      List pics = wordDocument.getPicturesTable().getAllPictures();
      if (pics != null) {
       for (int i = 0; i < pics.size(); i++) {
        Picture pic = (Picture) pics.get(i);
        try {
         pic.writeImageContent(new FileOutputStream(path
           + pic.suggestFullFileName()));
        } catch (FileNotFoundException e) {
         e.printStackTrace();
        }
       }
      }
      Document htmlDocument = wordToHtmlConverter.getDocument();
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      DOMSource domSource = new DOMSource(htmlDocument);
      StreamResult streamResult = new StreamResult(outStream);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.METHOD, "html");
      serializer.transform(domSource, streamResult);
      outStream.close();
      String content = new String(outStream.toByteArray());
      FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8");
     }
    }
    

    ###excel转html

    package excelToHtml;
    
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hwpf.converter.PicturesManager;
    import org.apache.poi.hwpf.converter.WordToHtmlConverter;
    import org.apache.poi.hwpf.usermodel.Picture;
    import org.apache.poi.hwpf.usermodel.PictureType;
    import org.w3c.dom.Document;
    
    
    public class PoiExcelToHtml {
    	final static String path = "D:\\poi-test\\excelToHtml\\";
    	 final static String file = "exportExcel.xls";
     public static void main(String args[]) throws Exception {
    	 
    	 InputStream input=new FileInputStream(path+file);
    	 HSSFWorkbook excelBook=new HSSFWorkbook(input);
    	 ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
    	 excelToHtmlConverter.processWorkbook(excelBook);
    	 List pics = excelBook.getAllPictures();
         if (pics != null) {
             for (int i = 0; i < pics.size(); i++) {
                 Picture pic = (Picture) pics.get (i);
                 try {
                     pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) );
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
             }
         }
         Document htmlDocument =excelToHtmlConverter.getDocument();
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         DOMSource domSource = new DOMSource (htmlDocument);
         StreamResult streamResult = new StreamResult (outStream);
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer serializer = tf.newTransformer();
         serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
         serializer.setOutputProperty (OutputKeys.INDENT, "yes");
         serializer.setOutputProperty (OutputKeys.METHOD, "html");
         serializer.transform (domSource, streamResult);
         outStream.close();
    
         String content = new String (outStream.toByteArray() );
    
         FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8");
     }
    }
    

    ###ppt转html
    其实只是ppt转图片,有了图片后放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程。

    package pptToImg;
    
    import java.awt.Dimension;   
    import java.io.File;   
    import java.io.FileInputStream;   
    import java.io.FileNotFoundException;   
    import java.io.FileOutputStream;   
    import java.io.IOException;   
      
    import java.awt.Color;   
    import java.awt.Dimension;   
    import java.awt.Graphics2D;   
    import java.awt.geom.Rectangle2D;   
    import java.awt.image.BufferedImage;   
      
    import org.apache.poi.hslf.model.TextRun;   
    import org.apache.poi.hslf.record.Slide;   
    import org.apache.poi.hslf.usermodel.RichTextRun;   
    import org.apache.poi.hslf.usermodel.SlideShow;   
      
    public class PPTtoImage {   
        public static void main(String[] args) {   
            // 读入PPT文件   
            File file = new File("D:/poi-test/pptToImg/test.ppt");   
            doPPTtoImage(file);   
        }   
      
        public static boolean doPPTtoImage(File file) {   
            boolean isppt = checkFile(file);   
            if (!isppt) {   
                System.out.println("The image you specify don't exit!");   
                return false;   
            }   
            try {   
      
                FileInputStream is = new FileInputStream(file);   
                SlideShow ppt = new SlideShow(is);   
                is.close();   
                Dimension pgsize = ppt.getPageSize();   
                org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();   
                for (int i = 0; i < slide.length; i++) {   
                    System.out.print("第" + i + "页。");   
                       
                    TextRun[] truns = slide[i].getTextRuns();      
                    for ( int k=0;k<truns.length;k++){      
                       RichTextRun[] rtruns = truns[k].getRichTextRuns();      
                      for(int l=0;l<rtruns.length;l++){      
                           int index = rtruns[l].getFontIndex();      
                            String name = rtruns[l].getFontName();                
                            rtruns[l].setFontIndex(1);      
                            rtruns[l].setFontName("宋体");  
    //                        System.out.println(rtruns[l].getText());
                       }      
                    }      
                    BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);   
      
                    Graphics2D graphics = img.createGraphics();   
                    graphics.setPaint(Color.BLUE);   
                    graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));   
                    slide[i].draw(graphics);   
      
                    // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径   
                    FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg");   
                    javax.imageio.ImageIO.write(img, "jpeg", out);   
                    out.close();   
      
                }   
                System.out.println("success!!");   
                return true;   
            } catch (FileNotFoundException e) {   
                System.out.println(e);   
                // System.out.println("Can't find the image!");   
            } catch (IOException e) {   
            }   
            return false;   
        }   
      
        // function 检查文件是否为PPT   
        public static boolean checkFile(File file) {   
      
            boolean isppt = false;   
            String filename = file.getName();   
            String suffixname = null;   
            if (filename != null && filename.indexOf(".") != -1) {   
                suffixname = filename.substring(filename.indexOf("."));   
                if (suffixname.equals(".ppt")) {   
                    isppt = true;   
                }   
                return isppt;   
            } else {   
                return isppt;   
            }   
        }   
      
    }  
    

    ppt转图片有个缺陷,就是ppt里不是宋体的字有些可能会变成框框。
    以上都需要引入poi的jar包。
    要实现在线预览,只需把转换得到的html在新标签页打开或者镶嵌到某块区域就可以展现了。

    展开全文
  • Java实现HTTP Get请求

    千次阅读 2018-11-14 15:28:02
    import org.apache.http.HttpEntity; import org.apache.... import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; ...
  • Java实现发送Get和Post请求

    千次阅读 2017-12-15 21:44:11
    前言 已经有几天没有写博客了 , 原因是最近生活中有大量的事情, 尽管每天都在学习 , 但是却没有将知识点记录在博客中 , 感觉这样非常不好 . 以后一定要坚持写博客 , ...Java发送Get请求 代码Java创建代理连接对象 /**
  • 使用java实现HTTP的GET请求

    千次阅读 2020-05-12 11:33:03
    在前几节我们详细讲解了http协议的相关信息,基于“知行合一”的原则,只有通过具体动手实践才有可能检验知识点被我们真正掌握,本节我们就使用代码实现http的get请求。 首先需要一个http服务器,基于简单原则,我...
  • java socket 实现get post 请求

    千次阅读 2012-06-19 23:37:33
    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.ne
  • java实现网络交互 get、post方法

    千次阅读 2014-01-04 13:33:23
    java最基层的方式实现Http的get和post方法
  • HttpURLConnection实现post public static String getPost(String urls,Map<String, String> params){ String message=""; try { //创建URL实例,打开URLConnection URL url=ne...
  • JAVA实现后端发送POST请求和GET请求

    千次阅读 2019-11-08 13:14:13
    用后端发起请求的原因是因为,可能在不同的电脑使用前端的...通过RestTemplate发送GET请求以及POST请求。中间问题还有挺多,时间比较急,研究比较浅,做的时候只追求了能使用即可。 GET请求 String resString = null...
  • java+httpclient实现Get、Post接口自动化案例 HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议...
  • Java实现发送http的get和post请求

    万次阅读 2018-01-26 10:16:13
    import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * j
  • java 实现 httppost 和 httpget

    千次阅读 2012-06-30 12:30:46
    httpclient-4.1.1.jar ... commons-logging-1.1.jar ...import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; impo
  • 主函数代码块: HttpClient httpClient = HttpClientBuilder.create().build(); // Get请求 URIBuilder uriBuilder = new URIBuilder(payurl); if (StringUtils.isNotEmpty(reqJson))...
  • 最近在研究接口,想通过java代码实现get、post的接口访问,然后再得到响应,最好是可以获取响应中的某一个字段。比如:java代码请求post请求后,得到响应,然后再获取指定的某一个响应字段。我想知道这个用代码怎么...
  • 项目中会遇到需要发送请求获取不同服务器中的资源,此时不能使用转发或者重定向,而使用httpclient可以实现。下面介绍httpclient中的get请求和post请求: GET方法: public static String doGet() { String result...
  • GET请求和POST请求有什么区别?GET请求的参数在URL的问号后面显示,而POST参数不在URL上;POST可以比GET请求更大的数据…一般的回答都是这样。...为了搞清楚GET和POST的区别,下面写了一个Java程序来接收HTTP请求。
  • 1.GET 请求 public static String doGet(String httpurl,String contentType) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果...
  • Java - Get object approximate size

    万次阅读 2019-03-06 14:58:02
    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!...package chimomo.learning.java.java; /** * @author Created by Chimomo * Measure the approximate size of an object in memo...
  • 使用 org.apache.http.impl.client.HttpClients 这么滴就可以实现get请求传递参数啦 但是现在需求是要往请求的header里面传cookie。 怎么Java代码实现? 关键代码 CloseableHttpClient httpCl...
  • 前言平时测试的时候可能会遇到使用Java发送http或者https请求的需求.网上找了一圈暂时没有发现比较称心方便...主要实现http/https的get和post请求,并支持设置代理抓包.只需要一个Java文件就搞定,不需要第三方库支持.
  • java代码实现http请求工具类封装 参数介绍: get方式请求:url:请求地址的字符串 post方式请求:url:请求地址的字符串 jsonString:json字符串 注意:json字符串的生成的方法如下 需要封装的json格式如下:...
  • Java实现http(post、get)请求

    万次阅读 2017-12-13 15:25:16
    protected final Log LOG = LogFactory.getLog(HttpClientUtil.class); private static HttpClientUtil instance; protected Charset charset; private HttpClientUtil(){} public static HttpClientUtil ...
  • 一个简单演示如果使用JAVA Socket实现HTTP GET请求数据与HTTP POST提交数据的客户端 希望让更多的人知道写HTTP客户端并不难,离开HTTP Client等第三方库,JAVA一样玩得转HTTP 连接.
  • public class HttpPlugin{  private static Log log = LogFactory.getLog(HttpPlugin.class);  @Override  public void init() {    }    public void sendGet...
  • java实现单链表

    万次阅读 多人点赞 2019-03-06 22:08:37
    链表是java数据结构中一种很基础很常见却也很重要的数据结构,JDK中许多内置jar包基于单链表实现,比如像我们熟悉的linkedList等,为什么要使用链表呢? 我们知道java中很多集合的底层是基于数组实现的,数组有一个...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,415,600
精华内容 566,240
关键字:

java实现get

java 订阅