简体   繁体   English

使用POST的Applet PHP通信

[英]Applet php communication using POST

so here is my problem. 所以这是我的问题。 I simply can't get my applet&php communication going. 我简直无法使applet&php通讯正常进行。 I'm using the below class for communication 我正在使用下面的类进行交流

 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;
   }
}

And this is the function within my applet that is calling it 这就是我的小程序中正在调用的函数

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

And last this is the simple php script that should show the results of POST. 最后,这是应该显示POST结果的简单php脚本。 Please help me, I've tried everything and i won't work...The error php gives me is "Undefined index "ime", "brojP", "brojH". 请帮助我,我已经尝试了一切,但我将无法正常工作...错误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 . ")");

        ?>

Why don't you use some kind of framework for HTTP communication? 为什么不使用某种HTTP通讯框架? In my experience Apache HTTP Client is excelent solution for such operations, it makes request very easy to implement eg. 以我的经验,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.

isn't that simple? 是不是很简单? You don't have to reinvent the wheel again:) 您不必重新发明轮子:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM