duange051858 2013-03-21 21:07
浏览 78

使用java客户端应用程序将条目添加到mysql数据库中

I'm having a bit of trouble with a college networks assignment at the moment. I've got a php bookstore project containing a database called "books", and a table called "books". I can create, update, delete books on my PHP Bookstore no problem, but the task of the assignment for college was to be able to create a HttpClientApp program that would be able to send a GET and POST to the bookstore adding in a new book into the database.

I'm not really sure if the code I've got for the HttpClient and HttpClientApp will be able to add a new book into the database. I was wondering if anyone could take a look at them both and see if I'm missing out on anything?

Here is the code in full for the MyHttpClient.java file: `

package com.example.bookstore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyHttpClient {

    /*This creates the method MyHttpResponse execute, with a parameter of MyHttpRequest request which
     * creates a variable called request that stores a reference to the MyHttpRequest object allowing us
     * to use the objects methods in the MyHttpClient.java., we also add the throws IOException which
     * will tell us if we have an error with the input or output in the program
     */
    public MyHttpResponse execute(MyHttpRequest request) throws IOException {

        /*
         * Creates a variable called host of type string which
         * stores reference for the method getHost() which is in
         * the MyHttpRequest object. We then create a variable
         * int port which also stores the reference to the method getPort()
         * from the MyHttpRequest which gives us the port number of the avaya server
         * we are contacting, if it is less than or equal to 0 it will be set to 80 as
         * a default
         */
        String host = request.getHost();
        int port = request.getPort();
        if (port <= 0) {
            port = 80;
        }

        /*
         * Create the variable bookSoc of type Socket and is given the paramters of host and port
         * which is used in creating the socket to connect to the server
         */

        Socket bookSoc = new Socket(host, port);

        /*
        * Declares a variable called response, which allows us to assign the MyHttpResponse object to the
        * response variable. This stores a reference to the MyHttpResponse Object and allows us to reference and use
        * the methods in the MyHttpResponse Object
        */
        MyHttpResponse response = new MyHttpResponse();

        /*
         * Creates the a variable fromServer of type BufferedReader which is given the parameter of new
         * InputStreamReader which then opens up the stream using the bookSoc.getInputStream method.
         */
        BufferedReader fromServer = new BufferedReader(new InputStreamReader(bookSoc.getInputStream()));
        /*The variable toServer of type PrintWriter creates the OutPutStream which allows to output to the
         * Avaya Server
         */
        PrintWriter toServer = new PrintWriter(bookSoc.getOutputStream(), true);
        String method = request.getMethod();


        /*
         * The if statement works by checking if the the Method call equals a GET then
         * create the string path and queryString to print out to the server the path and host
         * which we require
         */
        if (method.equals("GET")) {
            String path = request.getPath();
            String queryString = request.getQueryString();
            toServer.println("GET " + path + " " + "HTTP/1.0");
            toServer.println(queryString);
            toServer.println("GET " + host);
            toServer.println(+port);

            /*
             * Creates a variable called line of type String
             * which will then be used to store the fromServer message, then we creates
             * another var called status of type int which the substring which count the
             * characters given. Then set the Status var equal to 200 OK
             */
            String line;
            line = fromServer.readLine();
            int status = Integer.parseInt(line.substring(9, 12));
            response.setStatus(status);
            String descr = line.substring(13);
            response.setDescription(descr);

            /*
             * Once the above code has been executed the do while do while loop,
             * is then run, the first do while loop reads in a line from the server
             * if the line is not null and line length is greater than 0,
             * creates a name and value var and are added to the header.
             *
             * Then the while  creates a var sbuf of type StringBuilder which
             * creates a new StringBuilder, then the next do while prints out the body of the the
             * repsonse, we then print the host and port number data.
             */
            do {
                line = fromServer.readLine();
                if (line != null && line.length() > 0) {
                    String name = line.substring(0, line.indexOf(": "));
                    String value = line.substring(line.indexOf(": ") + 2);
                    response.addHeader(name, value);
                }
            } while (line != null && line.length() > 0);
            StringBuilder sbuf = new StringBuilder();          
            do {
                line = fromServer.readLine();
                if (line != null) {
                    sbuf.append(line + "
");
                }

            } while (line != null);
            String body = sbuf.toString();
            response.setBody(body);

            System.out.println("host: " + host);
            System.out.println("port: " + String.valueOf(port));
        } 



        /*
         * if the method call is for the POST then the code below is executed which is
         * executing the same code as the above if statment except for that it is a POST method instead
         * of a GET method.
         */
        else if (method.equalsIgnoreCase("POST")) {


            String path = request.getPath();
            String queryString = request.getQueryString();
            toServer.println("POST " + path + " " + "HTTP/1.0");
            toServer.println();
            toServer.println(queryString);

            String line;
            line = fromServer.readLine();


            int status = Integer.parseInt(line.substring(9, 12));
            response.setStatus(status);

            String descr = line.substring(13);
            response.setDescription(descr);

            do{             
                line = fromServer.readLine();
                if (line != null && line.length() > 0) {

                    String name = line.substring(0, line.indexOf(": "));
                    String value = line.substring(line.indexOf(": ") + 2);
                    response.addHeader(name, value);

                }
            } 
            while (line != null && line.length() > 0);

            StringBuilder sb = new StringBuilder();
            do 
            {
                line = fromServer.readLine();
                if (line != null) {
                    sb.append(line).append("
");
                }

            } while (line != null);
            String body = sb.toString();

            response.setBody(body);

            System.out.println("host: " + host);
            System.out.println("port: " + String.valueOf(port));


        }
        /*Close the socket*/
        bookSoc.close();
        /*return the response*/
        return response;
    }
}

`

Here's the full code for the MyHttpClientApp.java file:

`

package com.example.bookstore;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MyHttpClientApp {

    public static void main(String[] args) {
        String urlString = null;
        URI uri;
        MyHttpClient client;
        MyHttpRequest request;
        MyHttpResponse response;

        try {
            //==================================================================
            // send GET request and print response
            //==================================================================
            urlString = "http://localhost:8888/bookstore/view_books.php";
            uri = new URI(urlString);
            client = new MyHttpClient();

            request = new MyHttpRequest(uri);
            request.setMethod("GET");
            response = client.execute(request);

            System.out.println("=============================================");
            System.out.println(request);
            System.out.println("=============================================");
            System.out.println(response);
            System.out.println("=============================================");

            //==================================================================
            // send POST request and print response
            //==================================================================
            urlString = "http://localhost:8888/bookstore/view_books.php";
            uri = new URI(urlString);
            client = new MyHttpClient();

            request = new MyHttpRequest(uri);
            request.setMethod("POST");
            request.addParameter("title", "Fringe");
            request.addParameter("firstName", "JJ");
            request.addParameter("lastName", "Abrams");
            request.addParameter("ISBN", "987654321349211");
            request.addParameter("publisher", "Sci-fi");
            request.addParameter("year", "2010");
            request.addParameter("price", "19.99");
            response = client.execute(request);

            System.out.println("=============================================");
            System.out.println(request);
            System.out.println("=============================================");
            System.out.println(response);
            System.out.println("=============================================");
        } catch (URISyntaxException e) {
            String errorMessage = "Error parsing uri (" + urlString + "): " + e.getMessage();
            System.out.println("MyHttpClientApp: " + errorMessage);
        } catch (IOException e) {
            String errorMessage = "Error downloading book list: " + e.getMessage();
            System.out.println("MyHttpClientApp: " + errorMessage);
        }
    }
}

`

I'm well aware I may be giving a vauge question so please feel free to ask me to post some more code etc.

  • 写回答

1条回答 默认 最新

  • dragon0118 2013-03-21 21:28
    关注

    your java code looks OK, but I would take a lot of the questions out of the client, and just use the HttpURLConnection utility instead of doing it all yourself: http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html

    Paste your server side code (php) to verify. Also does your server not need any GET or POST parameters? Because right now your request is empty, which is fine, just making sure you aren't forgetting to send something.

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line