Служба отдыха доступна в браузере, а не в коде Java - PullRequest
0 голосов
/ 15 февраля 2019

Я создал спокойный веб-сервис, размещенный на сервере A. Я пытаюсь вызвать этот сервис, используя класс Java в среде vpn клиента.Служба при попадании из кода показывает мне ошибку как Соединение отказано , но доступно при вызове в браузере.

Тот же сервис, к которому я пытаюсь получить доступ из общедоступного интернета с тем же кодом, работаетхорошо.

Я использую URLConnection для вызова службы в коде Java.Также пытался применить приведенный ниже код, но не помогло.

connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

Каковы возможные причины этого?Есть предложения?

Редактировать: Код прилагается

private final String crlf = "\r\n";
    private String url;
    private String boundary;
    private final int bufferSize = 4096;

    public UploadFiles(String argUrl) {
        url = argUrl;
        System.out.println(url);
        logEntry(url);
        boundary = "---------------------------4664151417711";
    }

    public int post() throws MalformedURLException, IOException {
        String charset = "UTF-8";
        String param = "value";
        String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
        String CRLF = "\r\n"; // Line separator required by multipart/form-data.

        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);) {

            File fileDir = new File(HomeController.configBean.getFilePath());
            File[] listFiles = fileDir.listFiles();

            for (File file : listFiles) {
                // Send text file.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + file.getName() + "\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
                writer.append(CRLF).flush();
                Files.copy(file.toPath(), output);
                output.flush(); // Important before continuing with writer!
                writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
            }
            // End of multipart/form-data.
            writer.append("--" + boundary + "--").append(CRLF).flush();
        } catch (IOException ex) {
            Logger.getLogger(UploadFiles.class.getName()).log(Level.SEVERE, null, ex);
        }

// Request is lazily fired whenever you need to obtain information about response.
        int responseCode = ((HttpURLConnection) connection).getResponseCode();
        System.out.println(responseCode); // Should be 200

        return responseCode;
    } // post() method

Редактировать 2: Ошибка

java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at sun.net.NetworkClient.doConnect(Unknown Source)
        at sun.net.www.http.HttpClient.openServer(Unknown Source)
        at sun.net.www.http.HttpClient.openServer(Unknown Source)
        at sun.net.www.http.HttpClient.<init>(Unknown Source)
        at sun.net.www.http.HttpClient.New(Unknown Source)
        at sun.net.www.http.HttpClient.New(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown
Source)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Sou
rce)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
        at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown
Source)
        at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown S
ource)
        at testfileupload.UsingURLConnection.uploadFilesUsingURLConnecton(UsingU
RLConnection.java:42)
        at testfileupload.FormUploadTestController.lambda$0(FormUploadTestContro
ller.java:62)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Comp
ositeEventHandler.java:86)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventH
andlerManager.java:238)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventH
andlerManager.java:191)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(C
ompositeEventDispatcher.java:59)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDis
patcher.java:58)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispat
chChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDis
patcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispat
chChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDis
patcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispat
chChainImpl.java:114)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
        at javafx.event.Event.fireEvent(Event.java:198)
        at javafx.scene.Node.fireEvent(Node.java:8413)
        at javafx.scene.control.Button.fire(Button.java:185)
        at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Bu
ttonBehavior.java:182)
        at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorS
kinBase.java:96)
        at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorS
kinBase.java:89)
        at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.h
andleBubblingEvent(CompositeEventHandler.java:218)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Comp
ositeEventHandler.java:80)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventH
andlerManager.java:238)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventH
andlerManager.java:191)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(C
ompositeEventDispatcher.java:59)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDis
patcher.java:58)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispat
chChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDis
patcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispat
chChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDis
patcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispat
chChainImpl.java:114)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.event.Event.fireEvent(Event.java:198)
        at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
        at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
        at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
        at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotificatio
n.run(GlassViewEventHandler.java:381)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotificatio
n.run(GlassViewEventHandler.java:295)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEve
nt$354(GlassViewEventHandler.java:417)
        at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Quantum
Toolkit.java:389)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Glas
sViewEventHandler.java:416)
        at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
        at com.sun.glass.ui.View.notifyMouse(View.java:937)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.ja
va:191)
        at java.lang.Thread.run(Unknown Source) 

Редактировать 3:

Я получаю это соединение отказано ошибка в OutputStream output = connection.getOutputStream();

Редактировать 4:

Я даже попробовал следующеекод для добавления прокси.

System.setProperty("http.proxyHost", url.getHost()); // My restful service url hostname
System.setProperty("http.proxyPort", url.getPort()); // My restful service url port

Я что-то здесь не так делаю?Пожалуйста, предложите.

1 Ответ

0 голосов
/ 15 февраля 2019

Я попробовал это с примером API Почтальона, он прекрасно работает, печатая 200

public void UploadFiles(String argUrl) {
    url = argUrl;
    System.out.println(url);
    boundary = "---------------------------4664151417711";
}

public static void main(String...strings) throws MalformedURLException, IOException {
    String charset = "UTF-8";
    String param = "value";
    String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
    String CRLF = "\r\n"; // Line separator required by multipart/form-data.

    HttpURLConnection connection = (HttpURLConnection) new URL("https://postman-echo.com/post").openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    try { 
        OutputStream output = connection.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);

        File fileDir = new File("C:\\Test");
        File[] listFiles = fileDir.listFiles();

        for (File file : listFiles) {
            // Send text file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + file.getName() + "\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
            writer.append(CRLF).flush();
            Files.copy(file.toPath(), output);
            output.flush(); // Important before continuing with writer!
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        }
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    int responseCode = ((HttpURLConnection) connection).getResponseCode();
    System.out.println(responseCode); // Should be 200
    if(connection!=null) {
        connection.disconnect();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...