使用httpUrlConnection将数据发送到服务器

时间:2013-12-09 11:16:44

标签: java post get httpurlconnection

我正在尝试使用HTTP创建最简单的WebServer和客户端。我应该使用同时使用两个连接的隧道方式;一个是接收数据的GET连接,另一个是发送数据的POST连接。

以下是我的代码:

//client GET Request
setoURL(new URL("http://" + input.getIp() + ":" + input.getPort() + input.getUrlPath()));
conn = (HttpURLConnection) getoURL().openConnection();

conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.addRequestProperty("User-Agent", "VVTK (ver=40)");
conn.addRequestProperty("Accept", "application/x-vvtk-tunnelled");
conn.addRequestProperty("x-sessioncookie", uniqueId());
conn.addRequestProperty("Pragma", "no-cache");
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Authorization",/*The Authorization*/);
conn.getResponseCode();

//Client POST request
HttpURLConnection second2 = (HttpURLConnection) apiCommand.getoURL().openConnection();
second2.setRequestMethod("POST");
second2.setReadTimeout(5000);
second2.setRequestProperty("User-Agent", "VVTK (ver=40)");
second2.setRequestProperty("x-sessioncookie", xsession);
second2.setRequestProperty("Pragma", "no-cache");
second2.setRequestProperty("Cache-Control", "no-cache");
second2.setRequestProperty("Content-Length", "7");
second2.setRequestProperty("Expires", "Sun, 9 Jan 1972 00:00:00 GMT");
second2.setRequestProperty("VerifyPassProxy", "yes");
second2.setRequestProperty("Authorization", /*The Authorization*/);
second2.setDoOutput(true);
reqStream = new DataOutputStream(second2.getOutputStream());
reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();

in = new BufferedReader(new InputStreamReader(second.getInputStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
}

问题是未发送帖子请求。第一个连接((GET请求))将向我发送事件或所有响应。我永远不应该断开连接或从第二个连接(POST请求)获取数据。

问题

为什么不发送POST请求?

1 个答案:

答案 0 :(得分:1)

reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();

添加此行

reqStream.close();

查看以下代码。我从java发送参数通过GET或POST和文件通过POST发送到php。同时,数据将通过POST和GET两种方法发送。 Java代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package httpcommunication;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 *
 * @author me0x847206
 */
final public class HTTPCommunication {

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

        HTTPCommunication http = new HTTPCommunication("http://localhost/post/index.php");

        http.addParam("data0", "0");
        http.addParam("1");
        http.addParam("", "2");
        http.addFile( "", "txtFile.txt");
        http.addFile( "", "photo2");
        http.addFile( "photo3", "photo.png");

        http.viaGET();
        System.out.println("text = " + http.getLastResponse() );
    }

    HTTPCommunication(String url) {
        this.url = url;

        setFilePrefix("f_");
        setParamPrefix("p_");
        setEncoding("ISO-8859-1");

        defaultFileName = 0;
        defaultParamName = 0;

        params = new java.util.TreeMap<>();
        headers = new java.util.TreeMap<>();
        files = new java.util.TreeMap<>();
    }

    public void viaPOST() {
       send(POST_METHOD);
    }

    public void viaGET() {
        send(GET_METHOD);
    }

    public void setURL(String s) {
        url = s;
    }

    public boolean setEncoding(String s) {
        if(!java.nio.charset.Charset.isSupported( s ))
            return false;
        urlEncoding = s;
        return true;
    }

    public boolean setParamPrefix(String s) {
        if( "".equals( s ) )
            return false;
        paramPrefix = s;
        return true;
    }

    public boolean setFilePrefix(String s) {
        if( "".equals( s ) )
            return false;
        filePrefix = s;
        return true;
    }

    public String getURL() {
        return url;
    }

    public String getEncoding() {
        return urlEncoding;
    }

    public String getParamPrefix() {
        return paramPrefix;
    }

    public String getFilePrefix() {
        return filePrefix;
    }

    public String getLastResponse() {
        return lastResponse.toString();
    }

    public int getLastResponseCode() {
        return lastResponseCode;
    }

    public void addHeader(String key, String value) {
        if("".equals( key ))
            return;
        if(headers.containsKey( key )) {
            headers.remove( key );
        }
        headers.put( key, value);
    }

    public void addParam(String value) {
        addParam("", value);
    }

    public void addParam(String key, String value) {
        key = paramPrefix + ("".equals( key ) ? ("" + ++defaultParamName) : key);
        if(params.containsKey( key )) {
            params.remove( key );
        }
        params.put( key, value);
    }

    public void addFile(String path) {
        addFile("", path);
    }

    public void addFile(String name, String path) {
        name = filePrefix + ("".equals( name ) ? ("" + ++defaultFileName) : name);
        if(files.containsKey( name )) {
            files.remove( name );
        }
        files.put( name, path); 
    }

    public void reset() {
        headers.clear();
        params.clear();
        files.clear();
        defaultParamName = 0;
        defaultFileName = 0;
    }

    private void send(int type) {
        try {
            if( url.startsWith("https") )
                return;

            StringBuffer urlParams = new StringBuffer();

            for(String s : params.keySet()) {
                urlParams.
                        append("&").
                        append(URLEncoder.encode( s, urlEncoding)).
                        append("=").
                        append(URLEncoder.encode(params.get( s ) , urlEncoding));
            }

            System.out.println( urlParams + "" );

            URL object = new URL(
                    url + (POST_METHOD == type ? "" : ("?" + urlParams))
            );

            HttpURLConnection connection = (HttpURLConnection) object.openConnection();

            /*
                with that line or without, is same effect
            */
            //connection.setRequestMethod( POST_METHOD == type ? "POST" : "GET");

            connection.setDoOutput( true );
            connection.setDoInput( true );
            connection.setUseCaches( false );
            connection.connect();

            for(String s : headers.keySet()) {
                connection.setRequestProperty( s, headers.get( s ) );
            }

            try (DataOutputStream out = new DataOutputStream( connection.getOutputStream() )) {
                if( POST_METHOD == type ) {
                    out.writeBytes( urlParams.toString() );
                }

                for(String name : files.keySet()) {
                    out.writeBytes( "&" + URLEncoder.encode( name, urlEncoding) + "=");
                    writeFile( out, files.get( name ) );
                }

                out.flush();

                lastResponseCode = connection.getResponseCode();

                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    lastResponse = new StringBuffer();
                    while( null != (line = in.readLine()) ) {
                        lastResponse.append( line );
                    }
                }
            }
            connection.disconnect();
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }

    private void writeFile(final DataOutputStream out, final String path) {
        try {
            try (FileInputStream in = new FileInputStream(path)) {
                byte bytes[] = new byte[4096];
                int read, totalRead = 0;
                while( -1 != (read = in.read(bytes)) ) {
                    out.writeBytes( URLEncoder.encode( new String( bytes, 0, read, urlEncoding ), urlEncoding) );
                    totalRead += read;
                }
                System.out.println("totalRead from " + path + " = " + totalRead + " (bytes).");
            }
        } catch (Exception e) {
            System.out.println("Exception 2");
        }
    }

    public static final int POST_METHOD = 0;
    public static final int GET_METHOD = 1;

    private String paramPrefix;
    private String filePrefix;

    private int defaultFileName, defaultParamName;

    private final java.util.SortedMap<String, String> params;
    private final java.util.SortedMap<String, String> headers;
    private final java.util.SortedMap<String, String> files;

    private String url = "";
    private String urlEncoding;
    private StringBuffer lastResponse = new StringBuffer();
    private int lastResponseCode = 0;
}

php代码:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
            foreach($_POST as $key => $value) {
                echo "<br \>\$_POST['$key'] ";
                if( "f_" == substr( $key, 0, 2) ) {
                    echo " <= this is a file";
                    $file = fopen( $key, "wb");
                    fwrite( $file, $value );
                    fclose( $file );
                } else {
                    echo " = $value";
                }
            }
            foreach($_GET as $key => $value) {
                echo "<br \>\$_GET['$key'] = $value";
            }
        ?>
    </body>
</html>

Java输出:

run:
&p_1=1&p_2=2&p_data0=0
totalRead from txtFile.txt = 3961 (bytes).
totalRead from photo2 = 17990 (bytes).
totalRead from photo.png = 56590 (bytes).
text = <!DOCTYPE html><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <br \>$_POST['f_1']  <= this is a file<br \>$_POST['f_2']  <= this is a file<br \>$_POST['f_photo3']  <= this is a file<br \>$_GET['p_1'] = 1<br \>$_GET['p_2'] = 2<br \>$_GET['p_data0'] = 0    </body></html>
BUILD SUCCESSFUL (total time: 1 second)

写入conn.getOutputStream()的数据必须遵循以下格式: [&amp;] paramName = paramValue [&amp; paramName = paramValue]等等,其中paramName和paramValue必须用URLEncoder.encode(paramName,encodedFormat)编码; 在你的代码中,数据写入是一个不尊重这种格式的字符串,所以php不明白这是什么,名称或值?并忽略这个