关键词搜索

源码搜索 ×
×

Java快速验证项目API服务是否发布成功

发布2018-07-24浏览820次

详情内容

这里有三个知识点:a.HTTP的协议请求方式;b.Jackson的使用;c.Java的HttpClient模拟Http请求响应。最近通过.Net  MVC 实现了一套应用服务接口,因为Java同事始终无法正确的访问,我只好自己动手给写了个示例程序。Java也是我一直热爱从事开发的语言,因为工作需要通过.Net MVC提供了一套基于音视频服务的接口,所以在此记录下。

Maven 依赖配置

加入两类配置HttpClient和Jackson。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.orghttps://files.jxasp.com/image/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.boonya.httpclient</groupId>
  7. <artifactId>HttpClientTest</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <jackjson.version>2.8.8</jackjson.version>
  11. </properties>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.apache.httpcomponents</groupId>
  15. <artifactId>httpclient</artifactId>
  16. <version>4.5.2</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.fasterxml.jackson.core</groupId>
  20. <artifactId>jackson-core</artifactId>
  21. <version>${jackjson.version}</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>com.fasterxml.jackson.core</groupId>
  25. <artifactId>jackson-annotations</artifactId>
  26. <version>${jackjson.version}</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>com.fasterxml.jackson.core</groupId>
  30. <artifactId>jackson-databind</artifactId>
  31. <version>${jackjson.version}</version>
  32. </dependency>
  33. </dependencies>
  34. </project>

Jackson Json工具

最简单的就是提交JSON格式的数据,JSON的工具是很有必要的,可以实现对象的序列化和反序列化操作。

  1. package com.boonya.httpclient;
  2. import com.fasterxml.jackson.core.JsonFactory;
  3. import com.fasterxml.jackson.core.JsonGenerator;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import java.io.IOException;
  6. import java.io.StringWriter;
  7. /**
  8. * @ClassName: JSONUtil
  9. * @Description: TODO(功能描述)
  10. * @author: pengjunlin
  11. * @company: ******科技有限公司
  12. * @date 2018-07-21
  13. */
  14. public class JSONUtil {
  15. /**
  16. * 对象转json
  17. * @param obj object 对象
  18. * @return String
  19. * @throws IOException
  20. */
  21. public static String toJson(Object obj) throws IOException {
  22. ObjectMapper mapper = new ObjectMapper();
  23. StringWriter sw = new StringWriter();
  24. JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
  25. mapper.writeValue(gen, obj);
  26. gen.close();
  27. return sw.toString();
  28. }
  29. /**
  30. * json转对象
  31. * @param jsonStr json字符串
  32. * @param objClass 类名.class
  33. * @return 泛型
  34. * @throws Exception
  35. */
  36. public static <T> T toObject(String jsonStr, Class<T> objClass)
  37. throws Exception {
  38. ObjectMapper mapper = new ObjectMapper();
  39. return mapper.readValue(jsonStr, objClass);
  40. }
  41. }

HttpClient工具

这里提供两种请求方式:GET和POST。

  1. package com.boonya.httpclient;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.HttpStatus;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.util.EntityUtils;
  13. import java.io.IOException;
  14. import java.nio.charset.Charset;
  15. /**
  16. * @ClassName: HttpClientUtil
  17. * @Description: TODO(HttpClientUtil工具类)
  18. * @author: pengjunlin
  19. * @company: ******科技有限公司
  20. * @date 2018-07-19
  21. */
  22. public class HttpClientUtil{
  23. /**
  24. * get请求,参数拼接在地址上
  25. * @param url 请求地址加参数
  26. * @return 响应
  27. */
  28. public static String get(String url)
  29. {
  30. String result = null;
  31. CloseableHttpClient httpClient = HttpClients.createDefault();
  32. HttpGet get = new HttpGet(url);
  33. get.addHeader("Content-Type","application/json; charset=utf-8");
  34. get.setHeader("Accept", "application/json");
  35. CloseableHttpResponse response = null;
  36. try {
  37. response = httpClient.execute(get);
  38. if(response != null && response.getStatusLine().getStatusCode() == 200)
  39. {
  40. HttpEntity entity = response.getEntity();
  41. result =entity.getContent().toString();
  42. }
  43. return result;
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }finally {
  47. try {
  48. httpClient.close();
  49. if(response != null)
  50. {
  51. response.close();
  52. }
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. return null;
  58. }
  59. public static String post(String url,String jsonParams){
  60. HttpClient httpClient =HttpClients.createDefault();
  61. HttpPost httpPost=new HttpPost(url);
  62. httpPost.addHeader("Content-Type","application/json; charset=utf-8");
  63. httpPost.setHeader("Accept", "application/json");
  64. httpPost.setEntity(new StringEntity(jsonParams, Charset.forName("UTF-8")));
  65. try {
  66. HttpResponse response = httpClient.execute(httpPost);
  67. int statusCode = response.getStatusLine().getStatusCode();
  68. if (statusCode != HttpStatus.SC_OK) {
  69. System.err.println("Method failed:" + response.getStatusLine());
  70. }else{
  71. String result = EntityUtils.toString(response.getEntity());
  72. return result;
  73. }
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. return null;
  78. }
  79. }

编写接口业务实体

这里是一个简单的音视频资源查询实体类:

  1. package com.boonya.httpclient;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. /**
  5. * @ClassName: FileSourceMultiRequest
  6. * @Description: TODO(功能描述)
  7. * @author: pengjunlin
  8. * @company: ******科技有限公司
  9. * @date 2018-07-19
  10. */
  11. public class FileSourceMultiRequest implements Serializable
  12. {
  13. /// <summary>
  14. /// SIM卡号【必填】
  15. /// </summary>
  16. public String[] Sims ;
  17. /// <summary>
  18. /// 通道号(Channel小于0通道不生效)
  19. /// </summary>
  20. public int Channel ;
  21. /// <summary>
  22. /// 报警标志(最小值为0,不能为负数)
  23. /// </summary>
  24. public long[] Alarms ;
  25. /// <summary>
  26. /// 存储器类型(0:主存储器或灾备存储器,1:主存储器,2:灾备存储器)【必填】
  27. /// </summary>
  28. public int StorageType ;
  29. /// <summary>
  30. /// 码流类型(0:主码流或子码流,1:主码流,2:子码流)【必填】
  31. /// </summary>
  32. public int StreamType ;
  33. /// <summary>
  34. /// 开始时间(yyyy-MM-dd HH:mm:ss)【必填】
  35. /// </summary>
  36. public Date StartTime ;
  37. /// <summary>
  38. /// 结束时间(yyyy-MM-dd HH:mm:ss)【必填】
  39. /// </summary>
  40. public Date EndTime ;
  41. /// <summary>
  42. /// 音视频资源类型(0:音视频,1:音频,2:视频,3:视频或音频)
  43. /// </summary>
  44. public int DataType;
  45. public String[] getSims() {
  46. return Sims;
  47. }
  48. public void setSims(String[] sims) {
  49. Sims = sims;
  50. }
  51. public int getChannel() {
  52. return Channel;
  53. }
  54. public void setChannel(int channel) {
  55. Channel = channel;
  56. }
  57. public long[] getAlarms() {
  58. return Alarms;
  59. }
  60. public void setAlarms(long[] alarms) {
  61. Alarms = alarms;
  62. }
  63. public int getStorageType() {
  64. return StorageType;
  65. }
  66. public void setStorageType(int storageType) {
  67. StorageType = storageType;
  68. }
  69. public int getStreamType() {
  70. return StreamType;
  71. }
  72. public void setStreamType(int streamType) {
  73. StreamType = streamType;
  74. }
  75. public Date getStartTime() {
  76. return StartTime;
  77. }
  78. public void setStartTime(Date startTime) {
  79. StartTime = startTime;
  80. }
  81. public Date getEndTime() {
  82. return EndTime;
  83. }
  84. public void setEndTime(Date endTime) {
  85. EndTime = endTime;
  86. }
  87. public int getDataType() {
  88. return DataType;
  89. }
  90. public void setDataType(int dataType) {
  91. DataType = dataType;
  92. }
  93. }

测试访问接口

  1. package com.boonya.httpclient;
  2. import java.util.Date;
  3. /**
  4. * @ClassName: MainTest
  5. * @Description: TODO(功能描述)
  6. * @author: pengjunlin
  7. * @company: ******科技有限公司
  8. * @date 2018-07-19
  9. */
  10. public class MainTest {
  11. public static void main(String[] args) throws Exception{
  12. String url="http://10.10.10.10:18100/api/WebService/MultiSIMAlarmForJsonParam";
  13. FileSourceMultiRequest request=new FileSourceMultiRequest();
  14. request.setSims(new String[]{"",""});
  15. request.setChannel(1);
  16. request.setAlarms(new long[]{1});
  17. Date start=new Date();
  18. start.setTime(start.getTime()-86400);
  19. request.setStartTime(start);
  20. Date end=new Date();
  21. end.setTime(end.getTime()+86400);
  22. request.setEndTime(end);
  23. request.setStorageType(0);
  24. request.setStreamType(0);
  25. request.setDataType(0);
  26. System.out.println(HttpClientUtil.post(url,JSONUtil.toJson(request)));
  27. }
  28. }

运行此测试:

程序接口正常返回数据。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载