在 Java 中通过代理发送 SOAP 消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21403719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:30:22  来源:igfitidea点击:

Sending SOAP message by Proxy in Java

javasoapproxy

提问by Grains

I need to know how to set a Proxy and confirm that it is working.

我需要知道如何设置代理并确认它正在工作。

I have made a test program looking like this:

我制作了一个如下所示的测试程序:

enter image description here

在此处输入图片说明

Where you can specify a proxy address and port number.

您可以在其中指定代理地址和端口号。

(I found the address and port on: http://www.freeproxylists.net/)

(我在:http: //www.freeproxylists.net/上找到了地址和端口 )

The SOAP call is looking like this when "Use Proxy" is checked:

选中“使用代理”时,SOAP 调用如下所示:

        Socket socket = new Socket();
        SocketAddress sockaddr = new InetSocketAddress(PROXY_ADDRESS, PROXY_PORT);
        socket.connect(sockaddr, 10000);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(socket.getInetAddress(), PROXY_PORT));
        URL url = new URL(urlStr);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
        return connection.call(message, uc);

Problem here is that the last row SOAPConnection.call(..)dose not allow HttpURLConnectionas input and thereby gives:

这里的问题是最后一行SOAPConnection.call(..)不允许HttpURLConnection作为输入,从而给出:

Bad endPoint type

错误的端点类型

Any idea how to add a proxy address to a SOAP call and verify that the proxy is in use?

知道如何将代理地址添加到 SOAP 调用并验证代理是否正在使用中?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

public class TestProxy implements ActionListener {

    public JTextField proxyField;
    public JTextField portField;
    public JCheckBox useProxy;

    // GUI
    public TestProxy() {
        JFrame f = new JFrame("Proxy tester");
        f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));

        proxyField = new JTextField("103.247.43.218");
        portField = new JTextField("8081");
        useProxy = new JCheckBox("Use Proxy");

        JButton b = new JButton("Connect!");
        b.addActionListener(this);

        f.getContentPane().add(proxyField);
        f.getContentPane().add(portField);
        f.getContentPane().add(useProxy);
        f.getContentPane().add(b);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    // ACTION
    @Override
    public void actionPerformed(ActionEvent e) {

        SOAPMessage response = null;
        try {
            SOAPMessage msg = createSOAPRequest();
            String urlStr = "http://www.webservicex.net/CurrencyConvertor.asmx?WSDL";
            response = sendSOAPMessage(msg, urlStr);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (SOAPException e1) {
            e1.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        if (response == null)
            JOptionPane.showMessageDialog(null, "Null returned...");
        else
            JOptionPane.showMessageDialog(null, "Returned response!!!");
    }

    // SOAP CALL
    public SOAPMessage sendSOAPMessage(SOAPMessage message, String urlStr) throws SOAPException, MalformedURLException {

        String PROXY_ADDRESS = proxyField.getText();
        int PROXY_PORT = Integer.parseInt(portField.getText());
        try {
            SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
            SOAPConnection connection = factory.createConnection();
            if (useProxy.isSelected()) {
                Socket socket = new Socket();
                SocketAddress sockaddr = new InetSocketAddress(PROXY_ADDRESS, PROXY_PORT);
                socket.connect(sockaddr, 10000);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(socket.getInetAddress(), PROXY_PORT));
                URL url = new URL(urlStr);
                HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
                // This "call" is not allowed!!
                return connection.call(message, uc);
            } else {
                return connection.call(message, urlStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // SOAP MESSAGE
    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        return soapMessage;
    }

    public static void main(String[] args) {
        new TestProxy();
    }
}

采纳答案by Grains

Working sendSOAPMessage method that use proxy:

使用代理的工作 sendSOAPMessage 方法:

public static SOAPMessage sendSOAPMessage(SOAPMessage message, String url, final Proxy p) throws SOAPException, MalformedURLException {
    SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
    SOAPConnection connection = factory.createConnection();

    URL endpoint = new URL(null, url, new URLStreamHandler() {
        protected URLConnection openConnection(URL url) throws IOException {
            // The url is the parent of this stream handler, so must
            // create clone
            URL clone = new URL(url.toString());

            URLConnection connection = null;
            if (p.address().toString().equals("0.0.0.0/0.0.0.0:80")) {
                connection = clone.openConnection();
            } else
                connection = clone.openConnection(p);
            connection.setConnectTimeout(5 * 1000); // 5 sec
            connection.setReadTimeout(5 * 1000); // 5 sec
            // Custom header
            connection.addRequestProperty("Developer-Mood", "Happy");
            return connection;
        }
    });

    try {
        SOAPMessage response = connection.call(message, endpoint);
        connection.close();
        return response;
    } catch (Exception e) {
        // Re-try if the connection failed
        SOAPMessage response = connection.call(message, endpoint);
        connection.close();
        return response;
    }
}

回答by PopoFibo

You can use Java Proxyclass - more details here. In essence, you can try whether your specified Proxyaddress is reachableor not. In case it is you can establish a URLconnection (HTTP connection as shown below or your own protocol - like SOAP) EDIT:

您可以在此处使用 JavaProxy类 - 更多详细信息。本质上,你可以试试你指定的地址是不是。如果您可以建立连接(如下所示的 HTTP 连接或您自己的协议 - 如 SOAP) 编辑:ProxyreachableURL

Using SocketAddressto try using the port value

使用SocketAddress使用的端口值试试

   Socket socket = null;
        try {
            SocketAddress sockaddr = new InetSocketAddress(PROXY_ADDRESS,
                    PROXY_PORT);

            socket = new Socket();

            socket.connect(sockaddr, 10000);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                    socket.getInetAddress(), PROXY_PORT));

            if (socket.getInetAddress().isReachable(10000)) {
                URL url = new URL("http://www.popofibo.com");
                HttpURLConnection uc = (HttpURLConnection) url
                        .openConnection(proxy);
                System.out.println("Content: " + uc.getContentType());
                uc.connect();
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

In the above example, you establish a proxy connection and check if the InetAddressis reachable or not. If yes, you go forth and use your proxy to establish an http connection.

在上面的例子中,你建立了一个代理连接并检查它InetAddress是否可达。如果是,则继续使用代理建立 http 连接。

EDIT:Since isReachable()'s credibility is questionable, you can try catching the exceptions and buidling your own booleanflag, working example below.

编辑:由于isReachable()的可信度值得怀疑,您可以尝试捕获异常并构建自己的boolean标志,下面的工作示例。

Here you try the connection of the proxyusing its address and port through Socketconnection and catch the exceptions. I tested both the examples with my own proxy server and it works, it definitely fails for the IPmentioned by you in the example.

在这里,您尝试通过连接proxy使用其地址和端口进行Socket连接并捕获异常。我使用我自己的代理服务器测试了这两个示例并且它可以工作,对于IP您在示例中提到的,它肯定失败了。

public static void main(String[] args) {
        Socket socket = new Socket();
        boolean proxyReachable = false;

        SocketAddress sockaddr = new InetSocketAddress(PROXY_ADDRESS,
                PROXY_PORT);

        try {
            socket.connect(sockaddr, 10000);
            proxyReachable = true;
        } catch (SocketTimeoutException e) {
            proxyReachable = false;

        } catch (IOException e) {
            proxyReachable = false;
        }

        if (proxyReachable) {
            try {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                        socket.getInetAddress(), PROXY_PORT));

                URL url = new URL("http://www.popofibo.com");

                HttpURLConnection uc = (HttpURLConnection) url
                        .openConnection(proxy);
                System.out.println("Content: " + uc.getContentType());
                uc.connect();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Output (with a valid proxy address/port):

输出(具有有效的代理地址/端口):

Content: text/html; charset=UTF-8