无法从Java应用程序正确使用http POST方法

时间:2017-03-23 17:30:06

标签: java http servlets post

我正在开发一个Java桌面应用程序,它接受用户输入并使用HTTP POST方法对网站的API进行验证。如果用户输入的信息与网站的数据库匹配,则该方法应返回200 OK的响应代码,允许用户前进到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     

在通过Java应用程序运行POST方法之前,我们使用POSTMAN验证了此设置,它采用相同的输入,对数据库进行检查并提供200 OK的响应代码。

但是当通过Java应用程序提供相同的输入参数时,它会返回204 No Content found的响应代码。

整个申请的代码如下:

// FXML CONTROLLER CLASS     包认证;

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

//用于GUI的FXML代码

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

}

我是这些Servlet方法的新手,因此我无法理解为什么通过POSTMAN输入的输入参数有效,并且同样不能通过Java应用程序的POST方法调用。

很抱歉很长的代码和问题。请有人指导我出错的地方以及如何解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

自上次使用这些Apache工具以来,API已发生变化。所以我展示的可能不是确切的答案。但在我看来,您确实喜欢将参数放入响应中而不是帖子中,而且,您将以错误的顺序执行此操作。

为:

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

(可能)好:

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

您可能希望看一下这篇文章 - &gt; Sending HTTP POST Request In Java