//HttpClient发起请求
public static String sendUrlFile(String url, String jsonstr) {
String result = "";
try {
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(url);
FilePart filePart = new FilePart("file", new File("/root/桌面/文档/记录.txt"));
filePart.setCharSet("utf-8");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
//Part数组装需要传第的参数和文件等
Part[] parts = {new StringPart("username",jsonstr , "utf-8"),filePart};
MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(entity);
int code = httpclient.executeMethod(post);
//拿到响应结果
result = new String(post.getResponseBody(), "UTF-8");
//可释放连接
post.releaseConnection();
return result;
} catch (HttpException h) {
LOGGER.error("cause HttpException:" + h.getMessage());
} catch (Exception i) {
LOGGER.error("发送请求错误: url cause IOException:" + i.getMessage());
}
return "";
}
//接收请求服务器端 参数需要和发送端一致
@ResponseBody
@RequestMapping(value = “/login”)
public JsonResult revice(@RequestParam(“file”) MultipartFile file,@RequestParam(“username”)String username) throws IOException{
InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream("/root/桌面/ok.txt");
byte[] bs = new byte[1024];
int len;
while(-1 != (len = (in.read(bs)))){
out.write(bs);
}
JsonResult json = new JsonResult();
System.out.println();
json.setResult(“ok”);
return json;
}