生成excel&https请求排除证书发送formdata

本文介绍了如何使用Java通过WritableWorkbook创建Excel文件,以及如何发送包含FormData的HTTPS请求并解析返回的JSONObject。
摘要由CSDN通过智能技术生成
//生成excel
WritableWorkbook book = null;
		WritableSheet sheet;
		File file = null;
		try {
			// 禁止WritableWorkbook资源关闭时的GC操作
			WorkbookSettings workbookSettings = new WorkbookSettings();
			workbookSettings.setGCDisabled(true);
			// 创建文件
			file = new File(temPath + ".xls");//文件路径
			book = Workbook.createWorkbook(file, workbookSettings);
			WritableCellFormat format = new WritableCellFormat();
			format.setBackground(Colour.ORANGE);
			format.setAlignment(Alignment.CENTRE);
			sheet = book.createSheet("sheet1", 0);
			sheet.getSettings().setDefaultColumnWidth(15);
			if (dateFieldTitleList.size() > 3) {
				sheet.setColumnView(0, 20);
				sheet.setColumnView(1, 20);
			} else {
				sheet.setColumnView(0, 20);
			}
			for (int i = 0; i < dateFieldTitleList.size(); i++) {
				Label lable = new Label(i, 0, dateFieldTitleList.get(i));
				lable.setCellFormat(format);
				sheet.addCell(lable);
			}
			// 行
			for (int row = 0; row < detailDataList.size(); row++) {
				// 列
				for (int col = 0; col < detailFieldList.size(); col++) {
					String value = "";
						value = detailDataList.get(row).getValueAsString(detailFieldList.get(col));
					Label lable = new Label(col, row + 1, value);
					// 给sheet电子版中所有的列设置默认的列的宽度;
					sheet.addCell(lable);
				}
			}
			book.write();
		} catch (Exception e) {
			if (file != null) {
				file.delete();
			}
		} finally {
			if (book != null) {
				try {
					book.close();
				} catch (Exception e) {

				}
			}
		}
//https请求发送formdata

		BufferedReader in = null;
		HttpClient httpClient = null;
		PostMethod postMethod = null;
		StringBuffer inputLine = new StringBuffer();
		try {
			Protocol myhttps = new Protocol("https",
					new MySSLProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);

			httpClient = new HttpClient();
			HttpConnectionManagerParams managerParams = httpClient
					.getHttpConnectionManager().getParams();
			// 设置连接超时时间(单位毫秒)
			managerParams.setConnectionTimeout(30000);
			// 设置读数据超时时间(单位毫秒)
			managerParams.setSoTimeout(30000);

			postMethod = new PostMethod(url);
			postMethod.getParams().setContentCharset("utf-8");
			postMethod.setRequestHeader("Accept", "application/json");
			CustomFilePart filePart = new CustomFilePart(fileName, file);
			filePart.setCharSet("utf-8");
			Part[] parts = { filePart };
			postMethod.setRequestEntity(new MultipartRequestEntity(parts,
					postMethod.getParams()));
			int status = httpClient.executeMethod(postMethod);
			if (status != HttpStatus.SC_OK) {
				return null;
			}
			String str = "";
			in = new BufferedReader(new InputStreamReader(
					postMethod.getResponseBodyAsStream(), "UTF-8"));
			while ((str = in.readLine()) != null) {
				inputLine.append(str);
			}
			JSONObject result = JSON.parseObject(inputLine.toString());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (postMethod != null) {
					postMethod.releaseConnection();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//注:CustomFilePart需实现 org.apache.commons.httpclient.methods.multipart.FilePart,输出文件名需要重写sendDispositionHeader方法
	
//排除证书的httppost

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().
        		setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
        httpPost.setConfig(requestConfig);
        httpPost .addHeader("Content-Type", "application/json");

        try {
        	StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);
            
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {
            	throw new RuntimeException("请求出现错误,错误信息:" + response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger("errcode") == 0) {
                	result.remove("errcode");
                	result.remove("errmsg");
                    return result;
                } else {
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new OApiException(errCode, errMsg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (httpClient != null) {
                try {
              	  httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值