使用POST的Applet php通信

时间:2014-02-01 06:31:49

标签: java php post applet

所以这是我的问题。我根本无法得到我的applet和php通信。我正在使用以下课程进行交流

 import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;

public class POST {

   private String postParameters = "";
   private String webPage;
   private Vector<String>names;
   private Vector<String>values;

   public POST(){
      values = new Vector<String>();
      names = new Vector<String>();
   }

   /**
    * Adds a post variable (page.php?name=value)
    *
    * @param name the variable name
    * @param value the variable value, can be set to null, the url will simply become &name instead of &name=value
    * null
    */
   public void addPostValue(String name, String value) throws UnsupportedEncodingException {
      if (value == null) {
         try {
            postParameters += "&" + URLEncoder.encode(name, "UTF-8");
            names.add(name);
            values.add("");
         } catch (Exception ex) {
            ex.printStackTrace();
         }
      } else {
         postParameters += "&" + URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
         names.add(name);
         values.add(value);
      }
   }

   /**
    * Send post data without waiting for site output
    *
    * @return true if sending data terminated succesfully
    */
   public boolean sendPost() {
      try {
         if (webPage == null || webPage.equals("")) {
            throw new Exception("Empty url");
         }
         URL url = new URL(webPage);
         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
         wr.write(postParameters);
         wr.flush();
      } catch (Exception e) {
         e.printStackTrace();
         return false;
      }
      postParameters = "";
      return true;
   }

   /**
    * Sends data, then waits for site output
    *
    * @return null if no data is received, or a String containing the data
    */
   public String sendPostWithReturnValue() {

      String returnValue = "";
      try {
         if (webPage == null || webPage.equals("")) {
            throw new Exception("Empty url");
         }
         URL url = new URL(webPage);
         URLConnection conn =
                 url.openConnection();
         conn.setDoOutput(true);
         OutputStreamWriter wr =
                 new OutputStreamWriter(conn.getOutputStream());
         wr.write(postParameters);
         wr.flush();
         BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line;
         while ((line = rd.readLine()) != null) {
            returnValue += line + "\n";
         }
         wr.close();
         rd.close();
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
      postParameters = "";
      values = null;
      names=null;
      values = new Vector<String>();
      names = new Vector<String>();
      return returnValue;
   }

   /**
    * Sets the page to point at for sending post variables
    *
    * @param webPageToPointAt the page that will receive your post data
    */
   public void setWebPageToPointAt(String webPageToPointAt) {
      webPage = webPageToPointAt;
   }

   /**
    * @returns A Nx2 matrix containing all parameters name and values
    */
   public String[][] getParameters() {
      String[][] str = new String[names.size()][2];
      for (int i = 0; i < str.length; i++) {
         str[i][0] = names.get(i);
         str[i][1] = values.get(i);
      }
      return str;
   }
}

这是我的applet中调用它的函数

public void postajRezultat(int brojP, int brojH) throws IOException{
        P = Integer.toString(brojP);
        H = Integer.toString(brojH);


        POST post = new POST();
        post.addPostValue("brojH", H);
        post.addPostValue("brojP", P);
        post.addPostValue("ime", ime);

        post.setWebPageToPointAt(getCodeBase().toString() + "/includes/save.php");
        post.sendPost();

最后这是一个简单的php脚本,应该显示POST的结果。请帮助我,我已经尝试了一切,我将无法工作......错误php给我的是“未定义索引”ime“,”brojP“,”brojH“。

<?php
            mysql_connect ("127.0.0.1","root","vertrigo");
            mysql_select_db ("projekt_db");
            $ime=$_POST['ime'];
            $brojP=$_POST['brojP'];
            $brojH=$_POST['brojH'];
            echo("Test");
            echo($brojP . "" . $ime . "" . $brojH);

            $a=mysql_query("INSERT INTO highscore ('id', 'ime', 'brojP', 'brojH') VALUES (NULL, '" . $ime . "'," . $brojP . "," . $brojH . ")");

        ?>

1 个答案:

答案 0 :(得分:3)

为什么不使用某种框架进行HTTP通信? 根据我的经验,Apache HTTP Client是这种操作的优秀解决方案,它使请求非常容易实现,例如。

 HttpPost post=new HttpPost("where_to_send_post_request_url")
 post.setEntity(createdURLEncodedEntity) // here you add your post parameters as entity
 response=client.execute(post); // execute your post
 String page=EntityUtils.toString(response.getEntity()); // get response as string content eg html
 EntityUtils.consume(response.getEntity()); // release connection etc.

不是那么简单吗?你不必再重新发明轮子:)