【问题标题】:Unable to correctly use http POST method from a Java application无法从 Java 应用程序正确使用 http POST 方法
【发布时间】:2017-08-16 10:04:31
【问题描述】:

我正在开发一个 Java 桌面应用程序,该应用程序接受用户输入并使用 HTTP POST 方法针对网站的 API 对其进行验证。如果用户输入的信息与网站的数据库相匹配,该方法将返回 200 OK 的响应代码,允许用户前进到 Java 应用程序的下一页。

    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 控制器类 包认证;

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>

//主类

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 方法调用同样无效。

对于很长的代码和问题,我们深表歉意。请有人指导我哪里出错以及如何解决这个问题。提前致谢。

【问题讨论】:

    标签: java http servlets post


    【解决方案1】:

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

    不好:

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

    (可能)好:

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

    你不妨看看这篇文章 -> Sending HTTP POST Request In Java

    【讨论】:

    • 嗨,克里斯,尝试按照建议更改代码顺序。同样根据建议的参考文章包括代码 _HttpEntity entity = response.getEntity();而if else语句_实体对象返回一个空值。
    猜你喜欢
    • 1970-01-01
    • 2018-10-31
    • 2016-06-21
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多