Java 将带有HttpURLConnection的文件发布到PHP
我已经提到了这个链接 使用下面的代码,我试图将一个文件发布到本地PHP服务器。它总是在我的PHP文件中返回文件大小0Java 将带有HttpURLConnection的文件发布到PHP,java,http,post,client-server,httpurlconnection,Java,Http,Post,Client Server,Httpurlconnection,我已经提到了这个链接 使用下面的代码,我试图将一个文件发布到本地PHP服务器。它总是在我的PHP文件中返回文件大小0 public class FileUpload2 { String CRLF = "\r\n"; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { new FileUpload2
public class FileUpload2 {
String CRLF = "\r\n";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
new FileUpload2().put("http://localhost/test/test.php");
}
public void put(String targetURL) throws Exception {
String BOUNDRY = "==================================";
HttpURLConnection conn = null;
try {
// These strings are sent in the request body. They provide
// information about the file being uploaded
String contentDisposition = "Content-Disposition: form-data; name=\"userfile\"; filename=\"test.txt\"";
String contentType = "Content-Type: application/octet-stream";
// This is the standard format for a multipart request
StringBuffer requestBody = new StringBuffer();
requestBody.append("--");
requestBody.append(BOUNDRY);
requestBody.append(CRLF);
requestBody.append(contentDisposition);
requestBody.append(CRLF);
requestBody.append(contentType);
requestBody.append(CRLF);
requestBody.append("Content-Transfer-Encoding: binary" + CRLF);
requestBody.append(CRLF);
requestBody.append(new String(getFileBytes("test.txt")));
requestBody.append("--");
requestBody.append(BOUNDRY);
requestBody.append("--");
requestBody.append(CRLF);
// Make a connect to the server
URL url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDRY);
conn.setRequestProperty("Cache-Control", "no-cache");
// Send the body
DataOutputStream dataOS = new DataOutputStream(
conn.getOutputStream());
dataOS.writeBytes(requestBody.toString());
dataOS.flush();
dataOS.close();
// Ensure we got the HTTP 200 response code
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new Exception(String.format(
"Received the response code %d from the URL %s",
responseCode, url));
}
// Read the response
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytesRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
String response = new String(bytesReceived);
System.out.println(response);
// TODO: Do something here to handle the 'response' string
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
public byte[] getFileBytes(String file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = this.getClass().getResourceAsStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1)
ous.write(buffer, 0, read);
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
// swallow, since not that important
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
// swallow, since not that important
}
}
return ous.toByteArray();
}
PHP文件
<?php
move_uploaded_file($_FILES['userfile']["tmp_name"], "test.txt");
//file_put_contents("test", "asd".$_FILES['userfile']);
print_r($_FILES);
print_r($_REQUEST);
?>
提前谢谢 最后,我通过添加apachehttp客户端库而不是HttpUrlConnection解决了这个问题
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
/*if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}*/
CloseableHttpClient httpclient = HttpClients.createDefault();
InputStream responseStream = null ;
String responseString = "" ;
try {
HttpPost httppost = new HttpPost("http://localhost/test/test.php");
FileBody bin = new FileBody(new File("D:/Jeyasithar/Workspace/Java/TestJava/src/test.txt"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
responseStream = resEntity.getContent() ;
if (responseStream != null){
BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)) ;
String responseLine = br.readLine() ;
String tempResponseString = "" ;
while (responseLine != null){
tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
responseLine = br.readLine() ;
}
br.close() ;
if (tempResponseString.length() > 0){
responseString = tempResponseString ;
System.out.println(responseString);
}
}
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
/*
* ====================================================================
*向Apache软件基金会(ASF)授权
*一个或多个参与者许可协议。见通知文件
*与此工作一起分发以获取更多信息
*关于版权所有权。ASF许可此文件
*根据Apache许可证,版本2.0(
*“许可证”);除非符合规定,否则您不得使用此文件
*带着执照。您可以通过以下方式获得许可证副本:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,
*根据许可证分发的软件在
*“按原样”的基础上,没有任何
*种类,无论是明示的还是暗示的。请参阅许可证以获取详细信息
*管理权限和限制的特定语言
*根据许可证。
* ====================================================================
*
*该软件由许多人的自愿捐款组成
*代表Apache软件基金会的个人。更多
*关于Apache软件基金会的信息,请参阅
* .
*
*/
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入org.apache.http.HttpEntity;
导入org.apache.http.client.methods.CloseableHttpResponse;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.ContentType;
导入org.apache.http.entity.mime.MultipartEntityBuilder;
导入org.apache.http.entity.mime.content.FileBody;
导入org.apache.http.entity.mime.content.StringBody;
导入org.apache.http.impl.client.CloseableHttpClient;
导入org.apache.http.impl.client.HttpClients;
导入org.apache.http.util.EntityUtils;
/**
*示例如何使用多部分/表单编码的POST请求。
*/
公共类ClientMultipartFormPost{
公共静态void main(字符串[]args)引发异常{
/*如果(args.length!=1){
System.out.println(“未给出文件路径”);
系统出口(1);
}*/
CloseableHttpClient httpclient=HttpClients.createDefault();
InputStream responseStream=null;
字符串responseString=“”;
试一试{
HttpPost HttpPost=新的HttpPost(“http://localhost/test/test.php");
FileBody bin=newfilebody(新文件(“D:/Jeyasithar/Workspace/Java/TestJava/src/test.txt”);
StringBody注释=新的StringBody(“某种二进制文件”,ContentType.TEXT\u PLAIN);
HttpEntity reqEntity=MultipartEntityBuilder.create()
.addPart(“bin”,bin)
.addPart(“注释”,注释)
.build();
httppost.setEntity(reqEntity);
System.out.println(“正在执行请求”+httppost.getRequestLine());
CloseableHttpResponse response=httpclient.execute(httppost);
试一试{
System.out.println(“--------------------------------------------------------”;
System.out.println(response.getStatusLine());
HttpEntity当前性=response.getEntity();
if(最近性!=null){
System.out.println(“响应内容长度:+resEntity.getContentLength());
responseStream=resEntity.getContent();
if(responseStream!=null){
BufferedReader br=新的BufferedReader(新的InputStreamReader(responseStream));
字符串响应线=br.readLine();
字符串temperResponseString=“”;
while(responseLine!=null){
tempResponseString=tempResponseString+responseLine+System.getProperty(“line.separator”);
responseLine=br.readLine();
}
br.close();
if(tempResponseString.length()>0){
responseString=临时responseString;
系统输出打印LN(响应预算);
}
}
}
实体效用消耗(最近);
}最后{
response.close();
}
}最后{
httpclient.close();
}
}
}
为什么要将文本文件转换为字节,然后再转换回字符串?即使你有一个二进制文件,你也不应该仅仅用这些字节创建一个字符串,因为可能有一些控制字符会破坏你的请求,而应该使用base64或类似的方法对字节进行编码。顺便说一句,[error]=>3
是否表示至少有一个错误?如果是这样,您可以检查并发布错误。[错误]=>3表示根据PHP文档上传的部分文件当然您需要在接收端解码(顺便说一句,这不是加密,只是编码)。正如我所说,我建议不要将二进制数据的字节写入未编码的字符串,因为这可能会导致不需要的控制字符,如\0
(或unicode\u0000
)。如果您只有文本文件,那么我会将这些文件作为字符串而不是字节数组读取。附带说明:构造函数String(byte[])
将使用JVM的默认编码将字节转换为字符。如果该编码与用于创建字节数组的编码不匹配,您将无法获得预期的字符串(在编码重叠的少数情况下可能会起作用,但不要指望这一点)。因此,您可能希望将字符编码作为参数传递,例如使用String(byte
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
/*if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}*/
CloseableHttpClient httpclient = HttpClients.createDefault();
InputStream responseStream = null ;
String responseString = "" ;
try {
HttpPost httppost = new HttpPost("http://localhost/test/test.php");
FileBody bin = new FileBody(new File("D:/Jeyasithar/Workspace/Java/TestJava/src/test.txt"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
responseStream = resEntity.getContent() ;
if (responseStream != null){
BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)) ;
String responseLine = br.readLine() ;
String tempResponseString = "" ;
while (responseLine != null){
tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
responseLine = br.readLine() ;
}
br.close() ;
if (tempResponseString.length() > 0){
responseString = tempResponseString ;
System.out.println(responseString);
}
}
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}