先在swagger-editor中定义访问路径:
一定要定义produces为你所需要返回的mime类型,mime类型参考:http://www.w3school.com.cn/media/media_mimeref.asp
选择生成server端代码:
这里我选择的是jaxrs,是某个平台的java代码,具体是哪个平台没去研究
生成号代码之后,会有这样的代码
解压之后,用intellij打开该目录:
需要完善的代码都在impl里,里面是空代码:
具体如何调用,参考client端代码:
这样就配置好了,当然,我这里用得是jetty嵌入式开发,比较方便
继续话题,当jetty起来之后,比如本机的地址是localhost:33890,那么在测试代码里需要设置basePath,
@Test public void downloadGetTest() throws ApiException { String ddd= "111"; String ddd= "aaa"; String ddd= "zzz"; api.getApiClient().setBasePath("http://localhost:33890"); File response = api.downloadGet(ddd, ddd, ddd); System.out.println(response); // TODO: test validations }
这样请求就发过去了,server端impl/downloadimpl代码如下:
public Response downloadGet(String ddd, String ddd, String ddd, SecurityContext securityContext) throws NotFoundException { String filename = ddd+ "-" + ddd+ "-" + ddd; String path = "http://yjsy.cupl.edu.cn/attachments/article/2689/2017%E5%B9%B4%E7%A1%95%E5%A3%AB%E7%A0%94%E7%A9%B6%E7%94%9F%E7%BB%9F%E8%80%83%E6%8B%9F%E6%8B%9B%E7%94%9F%E8%AE%A1%E5%88%92.pdf"; byte[] getData = null; File tempFile = null; try { URL url = new URL(path); // 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 URLConnection uc = url.openConnection(); //读取文件 InputStream in = uc.getInputStream(); byte[] b = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = in.read(b)) != -1) { System.out.println("------ process continue -------"); bos.write(b, 0, len); } bos.close(); getData = bos.toByteArray(); //这里可以指定存到windows上的路径,一定要是已存在的目录 File directory = new File("d:\\"); //写文件 tempFile = File.createTempFile(filename, ".pdf", directory); tempFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tempFile); fos.write(getData); System.out.println(tempFile.length()); in.close(); fos.close(); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return Response.ok().entity(tempFile).build(); }
Response是swagger生成的一个抽象类
执行请求后,在本地d盘下就会生成一个pdf的文件,同时在c盘的临时文件夹下也会生成同样的文件
C:\Users\jack\AppData\Local\Temp\download-1392513126829992389
如果使用浏览器访问,也能在浏览器上显示出pdf的内容,如下: