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

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

问题描述

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

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.create

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

Client client = new Client(ch);

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

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

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