첫째, 배경을 사용하여
이 프로젝트에서 우리는 종종 상황이 가끔 파일 전송 등 다양한 도킹 시스템 데이터를 필요로 발생합니다. 데이터 만이 동일한 데이터베이스 서버, 다중 시스템 및 데이터베이스를 도킹하면, 우리는 데이터 공유의 목적을 달성하기 위해 오라클 동의어를 사용할 수 있습니다. 무엇보다 일반적인 것은 추가의 도움없이 다른 서버에서 실행중인 다른 응용 프로그램을 사용하려면 웹 서비스 기술을 통해 타사 소프트웨어 또는 하드웨어를 전문, 당신은 데이터의 상호 교환의 목적을 달성 할 수있다.
나는 아직 웹 서비스 기술을 노출하지 않았기 때문에, 그것은 HttpClient를 유사 웹 서비스 기술 데이터 교환 인터페이스를 달성하기 위해 지금이다. 그리고 이것은 또한 성공적인 전송을 연습을 통해 파일을 전송하고 궁극적으로 할 필요가 저작물 기록됩니다.
둘째, 서버는 데이터를 전송
1 액세스 경로까지 정상 제어기 세트를 작성;
2, 액세스에 로그인하지 않고 즉, 로그인 인증에서이 액세스 경로를 설정;
3, 서비스 콜을 확보하기 위해, 비즈니스 로직을 작성 상호 일반적인 비즈니스 로직을 통과하는 코드 만 검증 서비스 호출 코드를 합의 할 수있다.
코드 예 :
/**
* 发送普通数据接口
* @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;
}
}
셋째, 클라이언트는 데이터를 수신
1 표적 획득 HttpClient를 액세스 경로 및 파라미터 설정을 설정;
도 2는 HttpResponse에있어서, 상기 데이터 객체를 획득하고 HttpEntity를 획득, 송신 요구를 행한다;
3, 분석 데이터.
코드 예 :
/* 部分导包情况 */
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>")));
}
}