Jersey Client + set proxy

2019-02-01 12:48发布

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?

here is my client code:

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

7条回答
乱世女痞
2楼-- · 2019-02-01 13:13

I took user67871 and changed it a bit. What is nice about this approach is that it works with the system proxy on Windows. If you're on Windows and you configure a proxy in IE then this code will pick that up. When you are running Fiddler it also sets the system proxy so this makes it really easy to use Jersey and Fiddler together.

    Client client = new Client(new URLConnectionClientHandler(
            new HttpURLConnectionFactory() {
        Proxy p = null;

        @Override
        public HttpURLConnection getHttpURLConnection(URL url)
                throws IOException {
            try {
                if (p == null) {
                    List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
                    if (proxies != null) {
                        // just use the first one, I don't know if we should sometimes use a different one
                        p = proxies.get(0);
                    }
                    if (p == null) {
                        p = Proxy.NO_PROXY;
                    }
                }
                return (HttpURLConnection) url.openConnection(p);
            } catch (URISyntaxException ex) {
                throw new IOException(ex);
            }
        }
    }), config);
查看更多
登录 后发表回答