簡體   English   中英

從C客戶端到Java服務器的Http Post字符串給出錯誤400錯誤請求

[英]Http Post string from C client to Java server gives error 400 Bad Request

我有一個C客戶端和一個Java服務器(通過eclipse的Tomcat)。
1- C客戶端旨在對Java Server執行字符串的HTTP Post [Gives錯誤]
2-服務器具有一個localhost HTML表單頁,該表單頁用於保存接收到的所有字符串,並將其發布並寫入文件中[正常;請參見; 經過測試]

我遇到的問題是我無法使服務器成功接收並保存來自客戶端的字符串。 服務器將以“錯誤400錯誤的請求”響應。

但是,我能夠使服務器保存通過html表單頁面手動輸入的任何字符串。

我只需要讓客戶端代替我,就可以發布到html表單頁面(除非有一種更好的方法,讓客戶端無需表單頁面即可發布到服務器)。

我不是網絡和套接字編程方面的專家。 任何幫助是極大的贊賞。

這是Java服務器代碼:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

// Extend HttpServlet class
public class HelloForm extends HttpServlet {

  private OutputStream ostream;
// Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Parameter</b>: " //Displayed on result page NOT html page
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Parameter</b>: " //Displayed on result page NOT html page
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
      //printing result to console:
      System.out.println(request.getParameter("first_name"));
      System.out.printf("Parameter Entered: %s\n", request.getParameter("first_name"));

    ////printing results to file:
         {

try(PrintWriter serveroutput = new PrintWriter(new BufferedWriter(new FileWriter("/home/salimramjean/Desktop/ServerOutput.txt",true)))) {
    serveroutput.println(request.getParameter("first_name"));

            } 

        }       
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

服務器的HTML表單頁面:

    <html>
<body>
    <form action="HelloForm" method="POST">
        Parameter: <input type="text" name="first_name">
                    <br />
                    <input type="submit" value="Submit" />
    </form>
</body>
</html>
<?

這是C客戶端代碼:

    #include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */
#include <unistd.h>

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        8080; 
    char *host =        "192.168.1.65"; /* localhost: 127.0.0.1 or 192.168.1.65 */
    char *message_fmt = "POST /Parameter=%s&command=%s HTTP/1.1\n\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }



    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]); 
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    printf("ip address: %s\n\n", host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");
  /* send the request */
printf("Sending request\n\n");
total = strlen(message);
    sent = 0;
    do {
       //bytes = write(sockfd,a+sent,total-sent);
      bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total); //while (sent < 0);
    printf("Post request sent \n");

    //receive the response
    printf("Receiving response \n");
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response-received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while(received < total); //while (received < 0);
    printf("Response received\n");

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("\nServer Response:\n%s\n\n",response);

    return 0;
}

這是web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>FormServ</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>HelloForm</servlet-name>
        <servlet-class>HelloForm</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloForm</servlet-name>
        <url-pattern>/HelloForm</url-pattern>
    </servlet-mapping>

</web-app>

我如何運行和編譯的示例:
$ ./client IamSendingThisString提交

結果顯示在終端中:

Request:
POST /Parameter=IamSendingThisString&command=submit HTTP/1.1


ip address: 192.168.1.65

Sending request

Post request sent 
Receiving response 
Response received

Server Response:
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Date: Tue, 24 Feb 2015 09:22:15 GMT
Connection: close

0

正確的更改:

1- Edited POST header:
char *message_fmt = "POST /FormServ/HelloForm HTTP/1.1\r\nHost: %s:%d\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\nfirst_name=%s&last_name=%s\r\n"; 

2- Added content type:
char *contentType = "application/x-www-form-urlencoded";

3- Added Content length

您的C代碼沒有發送有效的HTTP / 1.1請求。 標頭中的每一行都必須以CRLR結尾(即“ \\ r \\ n”),標頭中必須緊跟一個空行(僅CRLF)。 請參閱: http//tools.ietf.org/html/rfc2616#page-31

您在此行中遇到的問題:“ POST / Parameter =%s&command =%s HTTP / 1.1 \\ n \\ n”

我不知道確切應該發送什么參數,但是它至少包含2個錯誤:

1)沒有符號? 在參數表之前。 如果您的Servlet部署在/中,則應為/?Parameter =%s&command =%s,而不是其他頁面,如/index.jsp

2)不以\\ r \\ n結尾(而是以\\ n \\ n結尾)

另外,也許您應該在結尾或請求中發送標頭Content-length,Content-type和其他\\ r \\ n。

嘗試找到一些有效的套接字客戶端示例並復制代碼。 例如http://examples.javacodegeeks.com/core-java/net/socket/send-http-post-request-with-socket/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM