http接口开发及调用
2016-02-19 15:14
477 查看
一般用http的post,尽量不用get;
开发中一般都使用org.apache.http的jar包,比较成熟,方便,易用;当然了,直接用java提供的也行
开发中一般都使用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(); } } }
相关文章推荐
- 关于Java的TCP编程中需要注意的一些坑,因为我踩过
- UTF-8 response of TIdHTTPServer with Free Pascal
- 基于HttpClient Jar包封装Java方法实现接口测试
- get/post方式调用http接口
- java调用Http请求 -HttpURLConnection学习
- The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar
- HTTP错误汇总(404、302、200……)
- 深入理解HTTP Session
- java.lang.ClassCastException: org.apache.shiro.web.servlet.ShiroHttpServletRequest cannot be cast to
- 如何生成每秒百万级别的 HTTP 请求?
- 关于高德地图转换经纬度为屏幕点,方便自定义需链接网络的marker且添加属性动画
- 简单区分Vmware的三种网络连接模式(bridged、NAT、host-only)
- 网络爬虫
- iOS开发之网络编程--4、NSURLSessionDataTask实现文件下载(离线断点续传下载) <进度值显示优化>
- Tomcat配置https协议详解(菜鸟的不二选择)
- HttpClient post parameters to Https(避免ssl错误)
- 在使用富文本编辑器kindeditor时,使用图片上传的功能报不允许访问路径***的HTTP谓词POST
- Ubuntu 14.04 手动编译安装apache httpd 服务器
- HTTP请求工具类
- TortoiseGit HTTPS方式保存密码最简单的方法