0

我想将两个变量的值从 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
4

2 回答 2

0

这是我在自己的小程序中使用的一些代码,用于将值(通过 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 方法(该方法发布我的“请求”值,并返回服务器的响应):

  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 脚本必须与小程序在同一台服务器上,否则这将不起作用。

于 2013-07-07T20:23:27.380 回答
0
java.net.UnknownServiceException:protocol doesn't support output

表示您使用的协议不支持输出。

getCodeBase()指的是一个文件的网址,所以像

file:/path/to/the/applet

协议为file,不支持输出。您正在寻找http支持输出的协议。

也许你想要getDocumentBase(),它实际上返回小程序所在的网页,即

http://www.path.to/the/applet
于 2013-07-07T09:48:40.117 回答