技术标签: JavaEE 接口-http-https-webservice
一般用http的post,尽量不用get;
开发中一般都使用org.apache.http的jar包,比较成熟,方便,易用;当然了,直接用java提供的也行
package com.XXXX.XXXX.service;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.ContentType;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/*
* Http接口 post
* 接收下属客户端上传样本,保存样本文件
* apache官网可以下载最新的jar包和demo
* http://hc.apache.org/downloads.cgi
*/
public class TestSampleUpload4client {
public static void main(String[] args) throws ClientProtocolException, IOException{
String url = "http://192.168.1.6:8010/xxxxxxxxxxx/sample/fileUpload.action";
// 配置要 POST 的数据
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 设置为浏览器兼容模式
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置请求的编码格式
multipartEntityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
ContentType TEXT_PLAIN = ContentType.create("text/plain", Charset.forName(HTTP.UTF_8));
//设置一致的编码格式极其重要,否则容易出现乱码,不管客户端是以什么语言什么方式进行调用,必须让其编码格式与接收端一致;
multipartEntityBuilder.addTextBody("userName", "admin",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("psd", "admin",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("mac", "ma2343344f1333",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("md5", "afy67juu8776a",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("type", "sample",TEXT_PLAIN);
//文件路径
File file = new File("D:\\glpt\\abc.txt");
multipartEntityBuilder.addBinaryBody("file", file);
/*
* 以下的参数提交方式也行
StringBody userName = new StringBody("admin", ContentType.create(
"text/plain", Consts.UTF_8));
StringBody password = new StringBody("admin", ContentType.create(
"text/plain", Consts.UTF_8));
// 把文件转换成流对象FileBody
FileBody bin = new FileBody(file);
multipartEntityBuilder.addPart("username", userName);
multipartEntityBuilder.addPart("password", password);
multipartEntityBuilder.addPart("file", bin);
*/
post(url,multipartEntityBuilder);
}
public static void post(String url,MultipartEntityBuilder multipartEntityBuilder) throws ClientProtocolException, IOException{
// 建立HttpPost对象
HttpPost httppost = new HttpPost(url);
HttpClient httpclient = HttpClientBuilder.create().build();
// 生成 HTTP POST 实体
HttpEntity httpEntity = multipartEntityBuilder.build();
httppost.setEntity(httpEntity);
// 发送Post,并返回一个HttpResponse对象
HttpResponse httpResponse = httpclient.execute(httppost);
// 以下两行可以得到指定的Header
// Header header = httpResponse.getFirstHeader("Content-Length");
// String headerVal = header.getValue();
HttpEntity httpEntity2 = httpResponse.getEntity();
System.out.println("httpResponse.getStatusLine().getStatusCode():"+httpResponse.getStatusLine().getStatusCode());
// 如果状态码为200,就是正常返回
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(httpEntity2);
// 得到返回的字符串
System.out.println(result);
// 如果是下载文件,可以用response.getEntity().getContent()返回InputStream
}else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
// 如果状态码为302
String locationUrl = httpResponse.getLastHeader("location").getValue();
post(locationUrl,multipartEntityBuilder);
}else {
String result = EntityUtils.toString(httpEntity2);
// 得到返回的字符串
System.out.println(result);
}
}
}
/**
*另一种处理方式
* @param args
* @throws UnsupportedEncodingException
* @throws IOException
* @throws ClientProtocolException
public static void main(String[] args) throws ClientProtocolException, IOException{
// TODO Auto-generated method stub
// POST的URL
String url = "http://192.168.10.203:8010/manageplatform/sample/sampleUpload.action";
// 建立HttpPost对象
HttpPost httppost = new HttpPost(url);
// 建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加参数
params.add(new BasicNameValuePair("userName", "admin"));
params.add(new BasicNameValuePair("psd", "admin"));
params.add(new BasicNameValuePair("mac", "mac3333333333"));
params.add(new BasicNameValuePair("md5", "md5555555555"));
params.add(new BasicNameValuePair("type", "sample"));
HttpClient httpclient = new DefaultHttpClient();
// 设置编码
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 发送Post,并返回一个HttpResponse对象
HttpResponse httpResponse = httpclient.execute(httppost);
// 以下两行可以得到指定的Header
Header header = httpResponse.getFirstHeader("Content-Length");
String headerVal = header.getValue();
HttpEntity httpEntity = httpResponse.getEntity();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 如果状态码为200,就是正常返回
String result = EntityUtils.toString(httpEntity);
// 得到返回的字符串
System.out.println(result);
// 打印输出
// 如果是下载文件,可以用response.getEntity().getContent()返回InputStream
}else {
String result = EntityUtils.toString(httpEntity);
// 得到返回的字符串
System.out.println(result);
}
}
*/
}
以上例子中http请求了一个url:http://192.168.10.xxx:8010/xxxxxxxx/sample/sampleUpload.action;
其中sampleUpload.action是用struts配置的;sampleUpload.action对应的action方法如下:
/**
* HTTP接口,
* 接收下属客户端及子管理中心上传样本,保存样本文件
*
* @return
*/
public void sampleUpload() {
OutputStream out = null;
try {
out = sResponse.getOutputStream();
String result = "Response=101;";
String path = sRequest.getSession().getServletContext().getRealPath("/");
System.out.println(path);
//用户认证
String userName = sRequest.getParameter("userName");
String psd = sRequest.getParameter("psd");
//此处省略了用户权限认证的操作;
String md5 = sRequest.getParameter("md5");
String mac = sRequest.getParameter("mac");
String type = sRequest.getParameter("type");
String ip = sRequest.getRemoteAddr();
if (StringUtils.isEmpty(md5) || StringUtils.isEmpty(mac) || StringUtils.isEmpty(type)) {
result = "Response=011;";
} else {
for (int i = 0; i < fileFileName.size(); i++) {
try {
String filename = fileFileName.get(i);
String savePath = StringUtils.isEmpty(UrlAddress.getUrl(type)) ? path + "WEB-INF/uploadPath/" + type : UrlAddress.getUrl(type);
if (!new File(savePath).exists()) {
new File(savePath).mkdirs();
}
filename = savePath + "/" + filename;
// sampleName = fileFileName.get(i);
FileOutputStream fos = new FileOutputStream(filename);
InputStream is = new FileInputStream(file.get(i));
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
filename = filename.replace('\\', '/');
result = "Response=000;";
result = sampleService.sampleUpload(type, md5, mac, filename, ip);
} catch (Exception e) {
result = "Response=101;";
e.printStackTrace();
}
}
}
//记录接口日志
sampleService.interfaceLogSave("1", mac, md5, ip, result);
//返回操作结果
out.write(result.getBytes());
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
一、Oracle定时任务简介Oracle定时任务是在oracle系统中一个非常重要的子系统,运用得当,可以大大提高我们系统运行和维护能力。oracle定时任务的功能,可以在指定的时间点自行执行任务。那么在实际工作中,什么样的场景会用到定时任务呢?下面是在实际工作中用到的真实业务场景举例在生成环境中,有时候需要在表中记录一些业务日志,系统运行时间长了之后,表中日志会越来越多,导致系统性能下降,这时候就需要用到定时任务,定时去删除表中一些时间年代比较久远垃圾数据。在某些业务场景中,明细表的数据量特别.
《Linux私房菜》阅读笔记整理chapter 0CPUcentral processing unit主要作用,管理和运算 (算数逻辑单元,控制单元)CPU的重点在与 运算和判断,这些数据来自于内存目前主流的CPU是双核以上,原本的单核是指仅有一个运算单元,多核是指在一个CPU壳子里装了多个运算内核CPU 的性能对比1 内部的微指令集2 CPU的频率 -- 每秒CPU的工作...
题目链接:https://ac.nowcoder.com/acm/contest/338/F题意:就是让你统计1~n中包含520的数的个数,n<= 1e18思路:数位DP中比较简单的了,dp[pos][pre1][pre2]代表着第pos位,前缀是pre1和pre2的不包含520的个数,最后用总数减去包含520的个数就是答案。#include<cstdio>#in...
博主在react框架中用了ant design组件库(以下简称ad),在vue框架中使用了element组件库(以下简称ele),最近遇到了两个需求,同用到了table组件的多选框功能,根据官方文档发现坑较多,踩坑如下,希望对新手有用。一、获取已选择的行信息adele二、数据保存后端,回弹已选项adele...
IR driver分析1、相关代码(1)相关代码位置/drivers/media/rc(2)kconfig文件分析根据kconfig文件语法说迷,可以分析得到目录代码里config RC_CORE 是被核心依赖的If RC_DECODERS对应框架驱动config LIRC 是lirc驱动config IR_LIRC_CODEC是LIRC解码程序,且依赖LIRCconfig IR_NEC_DECO...
1计算机主要由软件和硬件组成 软件又分为:系统软件和应用软件 多层结构计算机系统 2计算机体系结构与计算机组成(1)计算机体系结构是指那些可以被程序员所见到的计算机系统的属性,即概念性的结构或功能特性。(2)计算机组成是指如何实现计算机体系结构中所体现的属性,它包含了对许多程序员来说是透明的硬件细节。3计算机的基本组成 冯诺...
迁移之前,需先 确认哪些迁移已经应用到数据库了。查看应用到数据库的最后一次迁移ID 用 alembic current,(venv) D:\alchemy\c11>alembic currentINFO [alembic.runtime.migration] Context impl SQLiteImpl.INFO [alembic.runtime.migration] Will assume non-transactional DDL.0bad48b33ec2 (head)ale
/*文件名称:main.cpp 作者:王超 完成日期;2015年10月12日 版本号;v1.0 */#include #include "sqstack.h"int main(){ MultiBaseOutput(10, 2); return 0;}#include #include #inc
系列文章目录提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加例如:第一章 Python 机器学习入门之pandas的使用FPGA Verilog 串口发送使用modelsim进行Verilog仿真(包含testbench编写)FPGA 串口收发提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录系列文章目录前言一、SPI二、代码构思1.直接法2.状态机3.代码三、结果总结前言之前折腾Verilog折腾了几次,把串口收发弄出来了,但是总感觉问题还是挺
np.round()函数的做用:对给定的数组进行四舍五入,能够指定精度,同np.around()示例一:around(array, decimals=0, out=None)第一个参数指定数组第二个参数指定保留的小数点位数,缺省值为0,即取整数weba=np.array([1.23,2.31,31.23,66.23])print(np.round(a))print(np.around(a))'''result:[ 1. 2. 31. 66.][ 1. 2. 31. 66.]'
以下我用UBUNTU演示在LINUX环境下,扫描的结果通常是字符形式的如下:#sudo nmap -O 192.168.11.114Starting Nmap 6.40 ( http://nmap.org ) at 2018-10-24 09:27 CSTNmap scan report for ubuntu-14.04 (192.168.11.114)Host is up (0.000038s ...
思科路由器配置命令详解及实例本文档全篇共46页,详细介绍了思科路由器的配置命令教程详细解读 和小伙伴们一起来吐槽