Java使用显式发送

时间:2018-01-22 23:56:01

标签: java sockets httpurlconnection

有没有办法像这样发送HTTP POST:
1.在标题之前发送所有内容 做点什么...... 3.发送请求的重置(数据)

我尝试使用HTTPUrlConnection。但是,我没有找到像send()这样的方法来首先显式发送部分HTTP请求 我是否必须自己去Socket建立请求?

添加更多说明:
也许问题不够明确。
所以,我们都知道HTTP是在套接字连接之上。 所以,我所说的并不是改变通过套接字发送数据的顺序。 但是,我需要套接字将所有数据发送到标头,然后保持,保持连接。将发送另一个http请求以触发服务器端的偶数。然后完成发送所有数据。关闭连接。

这与服务器端实现有关。但是,这不属于我的问题。所以,请不要说服务器不应该这样设计。

正如我已经说过的,这可以通过从socket构建HTTP请求来完成。但是,我想看看是否有任何方法可以实现这一点,而无需在套接字级别执行所有操作。

这可以在python中轻松完成。

self._conn = httplib.HTTPConnection(ip, port, timeout=120)
self._conn.putrequest('POST', '/yourserveraddresss')
self._conn.putheader('format', 'InterleavedInt16')
self._conn.putheader('number-of-channels', '2')
self._conn.putheader('sample-rate', '16000')
self._conn.putheader('transfer-encoding', 'chunked')
self._conn.endheaders()

因此,这将打开连接并发送标头。连接将保持开放。所以,你可以做点什么。然后:

self._conn.send(chunked_data)
self._conn.close()

所以,在Java中。如果您使用HttpUrlConnection。你能这样做吗? 或者,也许像Apache HttpClient这样的其他工具?

3 个答案:

答案 0 :(得分:1)

不可能,您只能在请求的begening处发送标头,否则将被解释为消息的一部分。相关:https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html

HTTP 1.1基本上是连接上的文本,如果你想在服务器端口80中尝试打开套接字并通过管道发送文本,但你得到的只是ERRO 400无效请求。

修改:为了完善:

1-客户端在发送数据之前发送标头并等待一些事情:

package requestholder;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


public class RequestHolder {

    private static final DateFormat dateFormater= new SimpleDateFormat("yyyy-mm-aa hh:MM:ss");

    private static final String USER_AGENT = "Mozilla/5.0";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {

        URL url = new URL("http://localhost:8084/WebApplication2/Hold");

        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

        //no buffer, imediate flush
        httpConnection.setChunkedStreamingMode(1);

        //just in case....might matter for some servers
        httpConnection.setAllowUserInteraction(true);

        // Send post request
        httpConnection.setDoOutput(true);

        //add request headers
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("User-Agent", USER_AGENT);
        httpConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");



        StringBuilder someDataToSend = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            someDataToSend.append("word_:");
            someDataToSend.append(i);
            someDataToSend.append("  ");

        }

        DataOutputStream outPutWriter = new DataOutputStream(httpConnection.getOutputStream());

        //if ther's somenthing on the pipe (wich i doubt..), flush
        outPutWriter.flush();

        //************ represents slow logic here (Wait for other Thread/Connection), the headers has been sent and makes server wait for data
        Thread.sleep(20000);

        // send the remaing data
        outPutWriter.writeBytes(someDataToSend.toString());
        outPutWriter.flush();
        outPutWriter.close();

        //read the response from here
        int responseCode = httpConnection.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);

        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    }

   }

2-一个简单的servlet来证明这个概念:

package teste;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 */
@WebServlet(name = "Hold", urlPatterns = {"/Hold"})
public class Hold extends HttpServlet {

     private static final DateFormat format= new SimpleDateFormat("yyyy-mm-dd HH:MM:ss");
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //print the headers
        Enumeration<String> headerNames = request.getHeaderNames();
        String header;
        while (headerNames.hasMoreElements()) {
            header = headerNames.nextElement();
            System.out.println(format.format(System.currentTimeMillis())+":"+  header + ":" + request.getHeader(header));
        }


        BufferedReader dataReader = request.getReader();
        /* low on porpuse, to generate more lines*/
        char data[] = new char[1500];
        while(dataReader.read(data)>-1){
            System.out.println(format.format(System.currentTimeMillis())+":"+ new String(data));
        }

        //write a standart response
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Hold</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Hold at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

3-客户端输出:

运行:

发送&#39; POST&#39;请求网址:http://localhost:8084/WebApplication2/Hold

回复代码:200

Servlet Hold

Servlet保留在/ WebApplication2

4-最后在servlet输出中,标题和数据之间有18秒(How accurate is Thread.sleep?):

2018-24-23 22:01:02:user-agent:Mozilla / 5.0

2018-24-23 22:01:02:accept-language:en-US,en; q = 0.5

2018-24-23 22:01:02:host:localhost:8084

2018-24-23 22:01:02:接受:text / html,image / gif,image / jpeg,*; q = .2, / ; Q = 0.2

2018-24-23 22:01:02:连接:保持活力

2018-24-23 22:01:02:content-type:application / x-www-form-urlencoded

2018-24-23 22:01:02:transfer-encoding:chunked

2018-24-23 22:01:18:word_:0 word_:1 word_:2 word_:3 word_:4 word_:5 word_:6 word_:7 word_:8 word_:9

现金:

https://www.mkyong.com/java/java-https-client-httpsurlconnection-example/

Implement pause/resume in file downloading

NetBeans模板。

答案 1 :(得分:0)

使用HttpUrlConnection看起来无法做到这一点,因为这种工具的高级封装和灵活性较低。

我最终使用socket从头开始构建HTTP。这样你就可以在流的任何一点暂停,然后再继续。

答案 2 :(得分:-1)

你的问题毫无意义。根据定义,标题首先出现,因此“标题之前的所有内容”都不会引用任何内容。

  

我找不到像"movies"

这样的方法

没有一个。除非您使用固定长度或分块传输模式,否则在您执行需要输入的操作(例如获取响应代码或输入流)之前,不会发送请求。

目前尚不清楚这里的实际目的是什么。服务器在收到整个请求之前不会做任何事情,如果你在发送请求时乱七八糟,它可能会让你抽出时间。

编辑现在看来您不知道send()URL类,它们已经完成了您所需要的一切。我建议你查阅它们,并研究Java Tutorial的相关部分。