public class UploadService {
/**
* 默认的URL
*/
private static final String DEFAULT_HTTP_POST_URL = "http://localhost:8090/uploadfile";
private Logger logger = LoggerFactory.getLogger(UploadService.class);
private String url = DEFAULT_HTTP_POST_URL;
@Autowired
private HttpProvider httpProvider;
/**
*
* 初始化参数信息
*/
@PostConstruct
public void initConfig() {
url = Configuration.getInstance().getValue("url");
}
/**
*
* 上传文件到汇总统计程序
* @param filePath
* @throws IOException
*/
public void uploadFile(String filePath) throws IOException {
HttpClient client = httpProvider.getHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost(url);
File file = new File(filePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("file", cbFile);
post.setEntity(mpEntity);
HttpResponse response = client.execute(post);
String content = EntityUtils.toString(response.getEntity());
logger.debug("filePath :{} ,content :{}", filePath, content);
client.getConnectionManager().shutdown();
}
带源地址的Httpclient
@Service
public class HttpProvider {
private static final String DEFAULT_SCHEMA = "http";
private static final int DEFAULT_PORT = 80;
private static final String DEFAULT_LOCAL_IP = "127.0.0.1";
private String schema = DEFAULT_SCHEMA;
private int port = DEFAULT_PORT;
private String localIp = DEFAULT_LOCAL_IP;
/**
*
* 初始化配置
*/
@PostConstruct
public void initConfig() {
schema = Configuration.getInstance().getValue("schema");
port = Integer.valueOf(Configuration.getInstance().getValue("port"));
localIp = Configuration.getInstance().getValue("localIp");
}
/**
*
* 创建HttpClient客户端
* @return
*/
public HttpClient getHttpClient() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme(schema, port, new RouterSocketFactory(localIp)));
BasicClientConnectionManager connectManager = new BasicClientConnectionManager(schemeRegistry);
return new DefaultHttpClient(connectManager);
}
public class RouterSocketFactory extends PlainSocketFactory {
private String localAddressIp;
/**
*
* @param localAddress
*/
public RouterSocketFactory(final String localAddress) {
this.localAddressIp = localAddress;
}
/**
* 创建Socket连接
*/
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
InetSocketAddress localAddress, final HttpParams params) throws IOException {
InetSocketAddress local = null;
if (localAddress == null && localAddressIp != null && !"".equals(localAddressIp)) {
InetAddress routeAddress = InetAddress.getByName(localAddressIp);
local = new InetSocketAddress(routeAddress, 0);
}
return super.connectSocket(socket, remoteAddress, local, params);
}