在java中发送几个HTTP请求 - 与OuputStreamWriter有关吗?

[英]Sending several HTTP Requests in java - problem with OuputStreamWriter?


I am using Java in order to send HTTP Requests to webservices. I manage to send one, but I cannot send two. This is a part of my code (some parts removed for readability :

我正在使用Java来将HTTP请求发送到webservices。我设法送一个,但我不能送两个。这是我的代码的一部分(为了便于阅读,删除了一些部分:

try {
String data =  "<soap:Envelope xmlns:soap= ... datas xml ... </soap:Envelope>";
URL url = new URL(".......url........");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "text/xml");
conn.addRequestProperty("SOAPAction", .......action.......");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); // fail here for the second request

//write parameters
writer.write(data);
writer.flush();

// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {answer.append(line);
}
    writer.close();
reader.close();

//Output the response
String str=answer.toString();
// conn.disconnect(); // Should I put it ?
label.setText(str);
} 

catch (Exception ex) {label.setText(ex.getMessage());}

This request works fine. If I put the same after and do some tests, I find that it does not work (I change the names of variables, in case..). I have found that it fails at the line with the OuputStreamWriter. I get this error with getMessage in the exception :

这个要求很好。如果我把它放在后面并进行一些测试,我发现它不起作用(我改变变量的名称,以防万一..)。我发现它在使用OuputStreamWriter的行中失败了。我在异常中使用getMessage得到此错误:

access denied (java.net.SocketPermission ....url..... connect,resolve)

访问被拒绝(java.net.SocketPermission .... url ..... connect,resolve)

How could I fix it ? I figure out it is possible to send several requests... Is the method disconnect() useful here ?

我该怎么办呢?我发现可以发送多个请求......方法disconnect()在这里有用吗?

I tried to send the request via an other class (in fact, I have a webpage and javascript call the requests one by one), and it does not work too..

我试图通过其他类发送请求(事实上,我有一个网页和javascript逐个调用请求),它也不起作用..

Thank you very much for any advice or help !

非常感谢您的任何建议或帮助!

===================== EDIT =======================

=====================编辑=======================

Here is a whole applet :

这是一个完整的小程序:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import netscape.javascript.JSException;
import netscape.javascript.JSObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Test extends JApplet {
private JSObject jso;
private JLabel label = new JLabel();

public void init(){
    this.setSize(300, 80);

    label.setHorizontalAlignment(JLabel.CENTER);
    label.setForeground(Color.blue);
    label.setText("hello world");

    this.getContentPane().add(label, BorderLayout.NORTH);
}

public void doJavascript(){
    label.setText("hellooooooooo");
}


public void closeConnect(String SECTK, String SESSID){
    jso = JSObject.getWindow(this);
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setForeground(Color.blue);
    try{
     String data ="dataaaaa";
     label.setText("yes2");
 URL url = new URL(".........url.............");
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.addRequestProperty("Content-Type", "text/xml");
 conn.addRequestProperty("SOAPAction", ".....url........");
 conn.setDoOutput(true);
 label.setText("yes25");
 OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
 label.setText("yes3");
 writer.write(data);
 writer.flush();

 StringBuffer answer = new StringBuffer();
 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
 String line;
 while ((line = reader.readLine()) != null) {
     answer.append(line);
 }
 writer.close();
 reader.close();
 //Output the response*/
    String str=answer.toString();
    conn.disconnect();
    label.setText(str);
 } 
 catch (Exception ex) {
// label.setText("nooo");
 label.setText(ex.getMessage());
}
this.getContentPane().add(label, BorderLayout.NORTH);
}
}

If I call doJavascript from a javascript file, it works. If I call closeConnect from the same javascript file, it does not work, and I retrieve in my label "yes25", which is just before the "OuputStreamWriter"...

如果我从javascript文件调用doJavascript,它可以工作。如果我从同一个javascript文件调用closeConnect,它不起作用,我在我的标签中检索“yes25”,它就在“OuputStreamWriter”之前......

I hope it is clear.

我希望很清楚。

Thanks for any help or advice

感谢您的帮助或建议

2 个解决方案

#1


0  

Is the second request going to a different server than where the applet was download from? If so, then that is the problem.

第二个请求是否发送到与applet下载的服务器不同的服务器?如果是这样,那就是问题所在。

Applets cannot connect to or retrieve resources from any third party server (any server other than the server it originated from).

小程序无法连接到任何第三方服务器(从其源自的服务器以外的任何服务器)连接或检索资源。

http://download.oracle.com/javase/tutorial/deployment/applet/security.html

I would recommend solving this problem by using RMI to have the applet communicate with the server, and have the server make the actual XML requests on the applet's behalf. This is really easy to do, and using the download server as a proxy like this enables applets to do all sorts of stuff that the security manager restricts them from doing.

我建议通过使用RMI让applet与服务器通信来解决这个问题,并让服务器代表applet发出实际的XML请求。这很容易做到,并且使用下载服务器作为这样的代理使applet可以执行安全管理器限制他们执行的各种操作。

#2


0  

I have fixed it : there is a security problem for calls from javascript to java for some kinds of methods - for example http requests : http://jdk6.java.net/plugin2/liveconnect/#SECURITY_MODEL

我已修复它:对于某些方法,从javascript到java的调用存在安全问题 - 例如http请求:http://jdk6.java.net/plugin2/liveconnect/#SECURITY_MODEL

So the code must bu changed like this :

所以代码必须改变如下:

final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

and

OutputStreamWriter writer;
                // This is needed as code called from Javascript does not have the rights to do this
                try
                {
                    writer = 
                        AccessController.doPrivileged(
                            new PrivilegedExceptionAction<OutputStreamWriter>() {
                                public OutputStreamWriter run() throws IOException {
                                    return new OutputStreamWriter(conn.getOutputStream());
                                }
                            }
                        );
                }
                catch (PrivilegedActionException e) {
                    // e.getException() should be an instance of IOException,
                    // as only "checked" exceptions will be "wrapped" in a
                    // PrivilegedActionException.
                    throw (IOException) e.getException();
                }

and

StringBuffer answer = new StringBuffer();
                BufferedReader reader;
                // This is needed as code called from Javascript does not have the rights to do this
                try
                {
                     reader = new BufferedReader(
                        AccessController.doPrivileged(
                            new PrivilegedExceptionAction<InputStreamReader>() {
                                public InputStreamReader run() throws IOException {
                                    return new InputStreamReader(conn.getInputStream());
                                }
                            }
                        )
                    );
                }
                catch (PrivilegedActionException e) {
                    // e.getException() should be an instance of IOException,
                    // as only "checked" exceptions will be "wrapped" in a
                    // PrivilegedActionException.
                    throw (IOException) e.getException();
                }
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/07/01/72061a229c52d82eb855c674c2bac5de.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告