Only Execute Code on Certain Requests Java

Go To StackoverFlow.com

0

I am building a little API for class and the teacher supplied us with a link to a tutorial that provided a simple webserver that implements Runnable.

I have already written some code that will parse arguments the arguments ( or at least get me the request string ) and some code that will return some simple xml.

however I think certain requests like the one for the favicon are sent I think it is messing up my code. I wrapped that in an if else but it does not seem to be working.

=====EDITED Because of Basic string comparison errors=====

package server;

import java.io.IOException;


import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.*;
import java.io.*; 
import java.net.*;
import parkinglots.*;

/**
import our API 
*/
public class WorkerRunnable implements Runnable{

protected Socket clientSocket = null;
protected String serverText   = null;

public WorkerRunnable(Socket clientSocket, String serverText) {
    this.clientSocket = clientSocket;
    this.serverText   = serverText;
}

public Boolean authenticateAPI(String key){
    //Authenticate Key against Stored Keys

    //TODO: Create Stored Keys and Compare
    return true;
}

public void run() {
    try {
        InputStream input = clientSocket.getInputStream();
        OutputStream output = clientSocket.getOutputStream();
        long time = System.currentTimeMillis();


        //TODO: Parse args and output different formats and Authentication
        //Parse URL Arguments
        BufferedReader in = new BufferedReader( 
                new InputStreamReader(clientSocket.getInputStream(), "8859_1"));

        String request = in.readLine();

        //Server gets Favicon Request so skip that and goto args
        System.out.println(request);
        if ( !"GET /favicon.ico HTTP/1.1".equals(request) && !"GET / HTTP/1.1".equals(request) && !"".equals(request) ){

            String format = "", apikey ="";

            System.out.println("I am Here");

            String request_location = request.split(" ")[1];
            String request_args = request_location.replace("/","");
            request_args = request_args.replace("?","");
            String[] queries = request_args.split("&");

            System.out.println(queries[0]);

            for ( int i = 0; i < queries.length; i++ ){
                if( queries[i].equals("format") ){
                    format = queries[i].split("=")[1];
                }
                else if( queries[i].equals("apikey") ){
                    apikey = queries[i].split("=")[1];
                }
            }

            if( apikey.equals("") ){
                apikey = "None";
            }

            if( format.equals("") ){
                format = "xml";
            }

            System.out.println("format: "+format);

            Boolean auth = authenticateAPI(apikey);

            if ( auth ){
                if ( format.equals("xml")){
                    // Retrieve XML Document
                    String xml = LotFromDB.getParkingLotXML();
                    output.write((xml).getBytes());
                }else{
                    //Retrieve JSON
                    String json = LotFromDB.getParkingLotJSON();
                    output.write((json).getBytes());
                }
            }else{
                output.write(("Access Denied - User is Not Authenticated").getBytes());
            }
        }else{
            output.write(("Access Denied Must Pass API Key").getBytes());
        }

        output.close();
        input.close();
        System.out.println("Request processed: " + time);
    } catch (IOException e) {
        //report exceptions
        e.printStackTrace();
    }
}
}

Console output I get

GET /?format=json HTTP/1.1
I am Here
format=json
json
format: xml

It always returns the XML as well.

This is my first exposure to writing a web server and dealing with networking in Java, which frustrates me a lot in general, So any suggestions here are very appreciated.

Turned out to be this part here after getting a little help from everyone else. I was comparing the wrong part of the string so it never matched

                if( queries[i].split("=")[0].equals("format") ){
                    format = queries[i].split("=")[1];
                }
                else if( queries[i].split("=")[0].equals("apikey") ){
                    apikey = queries[i].split("=")[1];
                }
2012-04-04 05:25
by BillPull


5

For all you'r string comparison you need to use equals instead of ==

Example: if( format.equals("xml")) in the condition block also check if request is null

if (request != null && !"GET /favicon.ico HTTP/1.1".equals(request) 
  && !"GET / HTTP/1.1".equals(request) &&  !"".equals(request) )
2012-04-04 05:35
by keety


3

But you are using Java? In java you cannot compare String in this way

request != "GET /favicon.ico HTTP/1.1"

you need to write

!"GET /favicon.ico HTTP/1.1".equals(request)
2012-04-04 05:40
by dash1e


1

You should wait in a loop until server sends message. Try this when reading from socket:

    String request;
     while((request=in.readLine())==null);
     System.out.println(request);
2012-04-04 05:43
by mtyurt
Ads