[英]Passing value from applet to PHP
我想将两个变量的值从Java小程序发送到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
java.net.UnknownServiceException:protocol doesn't support output
表示您使用的协议不支持输出。
getCodeBase()
指向文件URL,所以类似
file:/path/to/the/applet
该协议是file
,不支持outout。 您正在寻找一个支持输出的http
协议。
也许您想要getDocumentBase()
,它实际上返回小程序所在的网页,即
http://www.path.to/the/applet
这是我与自己的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();
}
如您所见,我将所有值加起来发送到“内容”字符串中,然后调用我的requestFromDB方法(该方法将发布我的“ request”值,并返回服务器的响应):
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放在同一服务器上,否则将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.