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

注意!

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



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