after
reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();
add this line
reqStream.close();
View code below. I send, from java, parameters via GET or POST and files via POST, to php. In the same time, data will send via both methods, POST and GET.
Java code:
/*
* 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 code:
<!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 output:
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)
Data writed to conn.getOutputStream() must respect that format:
[&]paramName=paramValue[¶mName=paramValue] and so on, where paramName and paramValue must be encoded with URLEncoder.encode( paramName, encodedFormat);
In your code, data writting is an String that no respect that format, so php does not understand what is this, name or value? and ignore this