在发送http请求的时候关键在于request的封装
1、首先要先将上传的文件封装到HttpPostRequestEncoder中
HttpRequest request1 = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, url); HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // This encoder will help to encode Request for a FORM as POST. HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request1, false); bodyRequestEncoder.addBodyFileUpload("file", file, "application/x-zip-compressed", false);2、然后获取该封装的request中的List<InterfaceHttpData>
List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();
3、最后再重新创建一个HttpRequest,将上面封装获取到的List<InterFaceHttpData> 放入,然后通过channel直接发送该request就行了,该注意的是第二次创建的HttpPostRequestEncoder的第三个参数是true
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, url); request.headers().set(HttpHeaderNames.CONNECTION,HttpHeaderValues.CLOSE); HttpPostRequestEncoder bodyRequestEncoder2 = new HttpPostRequestEncoder(factory, request, true); bodyRequestEncoder2.setBodyHttpDatas(bodylist); bodyRequestEncoder2.finalizeRequest();