一般用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();
}
}

}

http接口开发及调用相关推荐

  1. Zebra 打印机 Android 端驱动接口开发及调用案例

    文章目录 Zebra 打印机 Android 端驱动接口开发及调用 GitHub 源码 开发步骤 环境配置 Zebra SDK 资源下载 Android 开发环境搭建 新建Android项目 新建 A ...

  2. java 红包接口开发_java调用微信现金红包接口的心得与体会总结

    这几天看了下之前写的有关微信支付的博客,看的人还是挺多的,看了下留言不知道是因为博客写的不够细还是什么情况,大多都找我要源码,我觉得吧程序员还是需要有这么一个思考的过程,因此没直接给源码,俗话说&qu ...

  3. 金蝶osf接口开发_调用OSF接口取待办任务总数报错!急

    总部老师,好: 在调用OSF接口取待办任务总数报错 Method failed: HTTP/1.1 404 Not Found org.apache.commons.httpclient.HttpEx ...

  4. 利用MyEclipse开发一个调用webservice接口的程序

    上一篇文章我们已经学习了如何使用Java 工具MyEclipse开发一个webservice接口,那么接口开发好了如何调用?接下来我们就来解决这个问题. 1:首先随便创建一个Java project选 ...

  5. php 动态彩码辨色 接口的调用_好用的云函数!后端低代码接口开发,零基础编写API接口...

    前言 在开发项目过程中,经常需要用到API接口,实现对数据库的CURD等操作. 不管你是专业的PHP开发工程师,还是客户端开发工程师,或者是不懂编程但懂得数据库SQL查询,又或者是完全不太懂技术的人, ...

  6. api 接口开发理论 在php中调用接口以及编写接口

    如: http://localhost/openUser.php?act=get_user_list&type=json 在这里openUser.php相当于一个接口,其中get_user_l ...

  7. python发送excel文件_Python操作Excel, 开发和调用接口,发送邮件

    接口开发: importflaskimporttoolsimportjson,redisimportrandom server= flask.Flask(__name__)#新建一个服务,把当前这个p ...

  8. 微信API接口、微信二次开发API调用

    微信API接口.微信二次开发API调用 微信协议接口调用-加微信好友及通过好友请求 加微信好友 /**       * 微信自动添加好友      * @author wechatno:tangjin ...

  9. python开发webService接口给java调用

    一.python webService接口 首先系统(winds)上要有python,本人安装的是:Anaconda2-5.0.1-Windows-x86.exe,环境搭建不会请自行百度. 其次要用p ...

最新文章

  1. c++ 遍历list_数据结构之图的遍历,一篇文章get全部考点
  2. 第四节:格式化器如何序列化类型实例
  3. 0b3398php,思想道德修养与法律基础(九江职业技术学院)知到2020题目及答案
  4. 【maven】Missing artifact javax.jms:jms:jar:1.1:compile
  5. interrupt、interrupted 、isInterrupted 区别
  6. linux cpu使用率1200%,linux下用top命令查看cpu利用率超过100%
  7. 自动性能统计信息(三)(Automatic Performance Statistics)
  8. vijos p1347(最大乘积(整数划分?))(25—100分)
  9. JPEG2000开发SDK及其特点
  10. linux nmap
  11. 同济大学研究生 计算机 哪个校区,同济大学研究生院在哪个校区?宿舍条件好不好?有哪些招生专业目...
  12. 虚拟仿真实验平台服务器需求,虚拟仿真实验中心平台建设方案.pptx
  13. 人工智能导论期末复习重点
  14. 【Web】CSS(No.21)Css经典案例(三)《爱宠知识》
  15. elasticsearch学习笔记--聚合函数篇
  16. Windows11图片密码的设置方法(用喜欢的图片作为开机密码)
  17. 如何查看office是否是永久激活
  18. java游戏张飞洗澡,张飞洗澡 刘备督战?在爆笑中搞懂电动汽车电池安全
  19. java百度地图离线LBS_Web版百度地图加载离线瓦片
  20. 企业OA即时通讯系统解决方案

热门文章

  1. ChatGPT镜像站点列表
  2. delphi 注册表操作之(读取、添加、删除、修改)
  3. 对学计算机而言,学历重要吗?
  4. 灵动微电子32位单片机MM32F0144C4Q引脚兼容替换MM32F031K8U6
  5. OpenCV边缘检测(二)——Sobel边缘检测
  6. Android系统恢复出厂设置方法-涵盖5.1 6.0 7.0 7.1 8.0 9.0
  7. 使用C#实现P2P应用程序(附原码) 分享
  8. CSS2中display:table属性的用法详解
  9. datepart函数返回星期几
  10. php 电脑桌面弹窗,Windows桌面添加我的电脑