Jersey 客户端 + 设置代理

编程入门 行业动态 更新时间:2024-10-11 01:21:22
本文介绍了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.HttpURLConnection;
import java.InetSocketAddress;
import java.Proxy;
import java.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", 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 14:55:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/733289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   Jersey

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!