0

I'm working on a Java Desktop application which accepts user input and validates it against the API of a website using the HTTP POST method. If the information entered by the user matches the website's database, the method is expected to return a response code of 200 OK allowing the user to progress to the next page of the Java Application.

    FOR THE CODE TO WORK, TWO INPUT PARAMETERS ARE REQUIRED

    1. license key = Smx22Mar
    2. deviceid = Laptop
    Content Type must be: application/x-www-form-urlencoded     

Before running the POST method through the Java application we verified this setup using POSTMAN, it takes the same input, checks it against the database and provides a response code of 200 OK.

But when the same input parameters are provided through the Java application, it returns a response code of 204 No Content found.

The code for the entire application is a follows:

//FXML CONTROLLER CLASS package authentication;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;


public class FXMLDocumentController implements Initializable {

    @FXML private TextField productKeyField;
    @FXML private TextField deviceIdField;

   @FXML private void Validate(ActionEvent event){

    String authKey=productKeyField.getText();
    String devicetype= deviceIdField.getText();

    boolean serverResponse=getServerKeyStatus(authKey,devicetype);
    System.out.println("Server Response"+serverResponse);

    if(serverResponse){ 
    //THIS IS THE DESIRED OUTPUT,WITH A STATUS OF 200 OK 
    System.out.println("License key is Authorised-------ACCESS GRANTED------");

    try {
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace(); }
    } else {
    System.out.println("Unauthorized License key");
    }
    }

    public static boolean getServerKeyStatus(String authkey,String devicetype){
    FXMLDocumentController http=new FXMLDocumentController();
    int status_code = 0;
    try {
        System.out.println(" Key is:"+authkey+ " Device Type is "+ devicetype);
        status_code=http.sendPost(authkey,devicetype);
        } catch (Exception e) {
        System.out.println("Exception while license key "+ e.getMessage());
        }
        if(status_code==200){
        //Logic to go to the next page
        return true;
        }
        else{
         System.out.println("Please enter the right KEY to proceed");
        return false;
        }
}


    private int sendPost(String authkey,String devicetype) throws Exception {

        final String USER_AGENT = "Mozilla/5.0";
        int status_code=0;
        try {

        String url = "http://www.example.com/api/software/activate";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", USER_AGENT);
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("licensekey",authkey));
        urlParameters.add(new BasicNameValuePair("deviceid",devicetype));

        HttpResponse response = client.execute(post);
        response.setEntity(new UrlEncodedFormEntity(urlParameters));

        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        status_code= response.getStatusLine().getStatusCode();                                

        BufferedReader rd = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
        result.append(line);
        }
        System.out.println(result.toString());
        } catch (Exception e) {
        }
      return status_code;
    }   


    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }
}

//FXML CODE FOR GUI

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" style="-fx-background-color: lightblue;" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="authentication.FXMLDocumentController">
    <children>
        <Button layoutX="144.0" layoutY="147.0" onAction="#Validate" text="Validate" />
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
      <TextField fx:id="productKeyField" layoutX="121.0" layoutY="52.0" />
      <TextField fx:id="deviceIdField" layoutX="121.0" layoutY="100.0" />
      <Label layoutX="20.0" layoutY="56.0" text="Authorisation key" />
      <Label layoutX="36.0" layoutY="104.0" text="Device type" />
    </children>
</AnchorPane>

//MAIN CLASS

public class Authentication extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

I am new to these Servlet methods, hence I'm unable to understand why the input parameters entered through POSTMAN works, and the same does not work through the POST method call from Java application.

Sorry about the very long code and question. Please could someone guide me where I'm going wrong and how to fix this. Thanks in advance.

Berch
  • 185
  • 1
  • 13

1 Answers1

0

The API has changed since the last time I used those Apache tools. So what I show may not be the precise answer. But it sure looks to me like you're putting your parameters into a response rather than the post, and further, you're doing it in the wrong order.

Bad:

    HttpResponse response = client.execute(post);
    response.setEntity(new UrlEncodedFormEntity(urlParameters));

(Possibly) Good:

    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response = client.execute(post);

You may wish to look at this post -> Sending HTTP POST Request In Java

Community
  • 1
  • 1
Chris Parker
  • 416
  • 2
  • 9
  • Hi Chris, tried changing the order of code as suggested. Also as per the suggested reference article included code _HttpEntity entity = response.getEntity(); and the if else statement_the entity object returns a null value. – Berch Mar 23 '17 at 19:39