[英]Rest service accessible in Browser not in Java code
我创建了一个托管在服务器A上的restful webservice。我试图在客户端的vpn环境中使用Java类来调用此服务。 从代码中点击的服务显示错误,因为连接被拒绝但可以在浏览器中调用时访问。
我尝试使用相同的代码从公共互联网访问相同的服务,它工作正常。
我正在使用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();
遇到此连接被拒绝错误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
我在这里做错了吗? 请建议。
我用Postman样本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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.