我想将两个变量的值从Java applet发送到PHP文件中),我尝试了以下代码。
try {
URL url = new URL(getCodeBase(),"abc.php");
URLConnection con = url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.print("score="+score);
ps.print("username="+username);
con.getInputStream();
ps.close();
} catch (Exception e) {
g.drawString(""+e, 200,100);
}
我收到以下错误:
java.net.UnknownServiceException:protocol doesn't support output
答案 0 :(得分:0)
java.net.UnknownServiceException:protocol doesn't support output
表示您使用的是不支持输出的协议。
getCodeBase()
指的是文件网址,如
file:/path/to/the/applet
协议为file
,不支持outout。您正在寻找支持输出的http
协议。
也许你想要getDocumentBase()
,它实际上会返回applet所在的网页,即
http://www.path.to/the/applet
答案 1 :(得分:0)
这是我在自己的applet中使用的一些代码,用于将值(通过POST)发送到我服务器上的PHP脚本:
我会像这样使用它:
String content = "";
content = content + "a=update&gid=" + gid + "&map=" + getMapString();
content = content + "&left_to_deploy=" + leftToDeploy + "&playerColor=" + playerColor;
content = content + "&uid=" + uid + "&player_won=" + didWin;
content = content + "&last_action=" + lastActionCode + "&appletID=" + appletID;
String result = "";
try {
result = requestFromDB(content);
System.out.println("Sending - " + content);
} catch (Exception e) {
status = e.toString();
}
正如您所看到的,我将所有值加起来发送到“content”字符串,然后调用我的requestFromDB方法(发布我的“请求”值,并返回服务器的响应):
public String requestFromDB(String request) throws Exception
{
// This will accept a formatted request string, send it to the
// PHP script, then collect the response and return it as a String.
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
// URL of CGI-Bin script.
url = new URL ("http://" + siteRoot + "/globalconquest/applet-update.php");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
printout.writeBytes (request);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
String str;
String a = "";
while (null != ((str = input.readLine())))
{
a = a + str;
}
input.close ();
System.out.println("Got " + a);
if (a.trim().equals("1")) {
// Error!
mode = "error";
}
return a;
} // requestFromDB
在我的PHP脚本中,我只需要查看$ _POST我的值。然后我会打印一个回复。
注意!出于安全原因,您的PHP脚本必须与applet位于同一服务器上,否则无效。