Use HttpClient to achieve a similar Web service data (file) transfer interface

First, use the background

In the project, we often encounter situations require multiple docking system data, sometimes including file transfer. If only the data docking, multiple systems and databases on the same database server, we can use Oracle synonym to achieve the purpose of data sharing. What is more common is through a Web service technologies to enable different applications running on different servers without the aid of additional, specialized third-party software or hardware, you can achieve the purpose of mutual exchange of data.

Because I have not yet been exposed Web service technology, it is now to achieve similar Web service technology data exchange interface by HttpClient. And this also needs to transfer files, through practice and ultimately be successful transmission, is hereby recorded.

Second, the server sends data

1, write a normal Controller set up an access path;

2, set this access path from login authentication, ie without login to access;

3, write the business logic, in order to secure a service call may be mutually agreed code, only validation service call code to go through normal business logic.

Code Example:

/**
  * 发送普通数据接口
  * @param serviceCode 服务调用码
  * @return 数据JSON对象
  * @author zhoujin
  * @date 2018-8-27
  */
@RequestMapping(value = "sendZbsmbList")
@ResponseBody
public JSONObject sendZbsmbList(String serviceCode){
    JSONObject result = new JSONObject();
    // 1.获取设定的服务调用码(从属性文件中读取)
    String currentCode = Global.getConfig("zbsmbServiceCode");
    if (currentCode.equals(serviceCode)) {
        // 2.获取需要发送的数据列表
        JSONArray jsonList = new JSONArray();
        ……
        // 3.设定返回参数
        result.put("success", true);
        result.put("data", jsonList);
        result.put("message", "数据请求成功!");
    } else {
        result.put("success", false);
        result.put("message", "服务调用码错误!");
    }
    return result;
}
	
/**
  * 发送文件数据接口
  * @param fileId 文件ID
  * @param serviceCode 服务调用码
  * @return 文件内容
  * @author zhoujin
  * @throws IOException 
  * @date 2018-8-27
  */
@RequestMapping(value = "sendZbsmbStream")
public void sendZbsmbStream(String fileId, String serviceCode,HttpServletRequest request, HttpServletResponse response) throws IOException{
    InputStream inStream = null;
    // 0.获取HTTP输出流,数据将通过该输出流发送出去
    ServletOutputStream outStream = response.getOutputStream();
    response.setContentType("text/html;charset=utf-8");
    // 1.获取设定的服务调用码(从属性文件中读取)
    String currentCode = Global.getConfig("zbsmbServiceCode");
    if (currentCode.equals(serviceCode)) {
        // 2.获取该文件输入流
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", fileId);
        map.put("storagetype", shareFile.getStoragetype());
        try {
            inStream = fileService.downloadFile(map);
            byte[] buf = new byte[1024 * 10];
            int len = -1;
            while((len = inStream.read(buf)) != -1){
                outStream.write(buf, 0, len);
                outStream.flush();
	        }
        } catch (Exception e) {
            response.setContentLength(-1);
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                inStream.close();
            }
            if (outStream != null) {
                outStream.close();
            }
        }
    }else{
        response.sendError(801, "服务调用码错误!");    // 自定义状态码
        return null;
    }
}

Third, the client receives the data

1, target acquisition HttpClient, set the access path and a parameter setting;

2, performs the transmission request, obtain the HttpResponse, wherein the data objects and obtain the HttpEntity;

3, parsed data.

Code Example:

/* 部分导包情况 */
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/* Test-1 */
public static void getZbsmbList() throws Exception{
    // 1.获取HttpClient对象
    HttpClient httpclient = HttpClients.createDefault();
    // 2.设定访问路径
    HttpPost httppost = new HttpPost("http://localhost:9999/sendZbsmbList");
    httppost.setHeader("Accept-Encoding", "identity");
    // 3.设定参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
    nvps.add(new BasicNameValuePair("serviceCode", "csxt@zj_hqfusj"));    // 参数名-数据 
    httppost.setEntity(new UrlEncodedFormEntity(nvps)); 
    // 4.执行,发送请求
    String str = "";     
    HttpResponse resultRep = httpclient.execute(httppost);
    if (resultRep.getStatusLine().getStatusCode() == 200) {
        // 5.获取传输的数据并解析
        str = EntityUtils.toString(resultRep.getEntity());
        if (StringUtils.isNotBlank(str)) {
            ……
        }
    } else {
        System.out.println("服务访问失败!");
    }
}
	
/* Test-2 */
public static void getZbsmbStream1() throws Exception{
    // 1.获取HttpClient对象
    HttpClient httpclient = HttpClients.createDefault();
    // 2.设定访问路径
    HttpPost httppost = new HttpPost("http://localhost:9999/sendZbsmbStream");
    // 3.设定参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
    nvps.add(new BasicNameValuePair("fileId", "2ad4ec1fbf2048f3b12c089454cd901b"));    // 参数名-数据 
    nvps.add(new BasicNameValuePair("serviceCode", "csxt@zj_hqfusj"));    // 参数名-数据 
    httppost.setEntity(new UrlEncodedFormEntity(nvps)); 
     // 4.执行,发送请求
    HttpResponse resultRep = httpclient.execute(httppost);
    int statusCode = resultRep.getStatusLine().getStatusCode();
    if (statusCode == 200) {
         // 5.获取传输的数据并解析
        HttpEntity httpEntity = resultRep.getEntity();
        // 6.将HTTP中返回实体转化为输入流
        InputStream inStream = httpEntity.getContent();
        FileOutputStream outStream = new FileOutputStream(new File("F:\\TestService\\testService.zip"));
        byte[] buf = new byte[1024 * 10];
        int len = -1;
        while((len = inStream.read(buf)) != -1){
            outStream.write(buf, 0, len);
        }
        inStream.close();
        outStream.close();
        System.out.println("文件输出结束!");
    } else {
        String result = EntityUtils.toString(resultRep.getEntity());
        System.out.println(result.substring(result.indexOf("<h1>") + 4, result.indexOf("</h1>")));
    }
}

 

Published 47 original articles · won praise 16 · views 70000 +

Guess you like

Origin blog.csdn.net/zorro_jin/article/details/82908567