Jersey 客户端 + 设置代理 [英] Jersey Client + set proxy

查看:53
本文介绍了Jersey 客户端 + 设置代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I've a jersey client which i use to upload a file. I tried using it locally and everything works fine. But in production environment i've to set proxy. I browsed thru few pages but could not get exact solution. Can someone pls help me with this?

这是我的客户端代码:

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);

推荐答案

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

There is an easier approach, if you want to avoid more libraries in legacy projects and there is no need for Proxy Authentication:

首先你需要一个实现 HttpURLConnectionFactory 的类:

First you need a class which implements 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());

第三个是使用Client构造函数代替Client.create:

and third is to use the Client Constructor instead of Client.create:

Client client = new Client(ch);

当然你可以在ConnectionFactory中自定义Proxy的初始化.

Of course you can customize the initializing of the Proxy in the ConnectionFactory.

这篇关于Jersey 客户端 + 设置代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆