泽西客户端 + 设置代理

2022-09-03 17:37:01

嗨,我有一个球衣客户端,我用它来上传文件。我尝试在本地使用它,一切都很好。但是在生产环境中,我必须设置代理。我浏览了几页,但无法获得确切的解决方案。有人可以帮我吗?

这是我的客户端代码:

File file = new File("e:\\test.zip");
FormDataMultiPart part = new FormDataMultiPart();
part.bodyPart(new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
WebResource resource = null;

if (proxy.equals("yes")) {
    // How do i configure client in this case?
} else {
    // this uses system proxy i guess
    resource = Client.create().resource(url);
}

String response = (String) resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
System.out.println(response);

答案 1

有一种更简单的方法,如果你想避免在遗留项目中有更多的库,并且不需要代理身份验证:

首先,你需要一个实现:HttpURLConnectionFactory

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory;


public class ConnectionFactory implements HttpURLConnectionFactory {

    Proxy proxy;

    private void initializeProxy() {
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy.com", 3128));
    }

    public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
        initializeProxy();
        return (HttpURLConnection) url.openConnection(proxy);
    }
}

二是实例化com.sun.jersey.client.urlconnection.URLConnectionHandler

URLConnectionClientHandler ch  = new URLConnectionClientHandler(new ConnectionFactory());

第三种是使用构造函数而不是:ClientClient.create

Client client = new Client(ch);

当然,您可以在 中自定义代理的初始化。ConnectionFactory


答案 2

幸运的答案应该有效。这是我的版本:

ClientConfig config = new DefaultClientConfig();
Client client = new Client(new URLConnectionClientHandler(
        new HttpURLConnectionFactory() {
    Proxy p = null;
    @Override
    public HttpURLConnection getHttpURLConnection(URL url)
            throws IOException {
        if (p == null) {
            if (System.getProperties().containsKey("http.proxyHost")) {
                p = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(
                        System.getProperty("http.proxyHost"),
                        Integer.getInteger("http.proxyPort", 80)));
            } else {
                p = Proxy.NO_PROXY;
            }
        }
        return (HttpURLConnection) url.openConnection(p);
    }
}), config);

推荐