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

时间:2011-07-01 14:55:57

标签: java http sockets

我正在使用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());}

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

  

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

我该如何解决?我发现可以发送几个请求...... 方法disconnect()在这里有用吗?

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

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

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

这是一个完整的小程序:

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

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

我希望很清楚。

感谢您提供任何帮助或建议

2 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分:0)

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

所以代码必须改变如下:

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

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

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