我有一个对我有用的代码,可以将文件发送到服务器,我已经在销售应用程序中使用了它,但是我想在另一个应用程序中使用它,但它对我不起作用。
String sourceFileUri = root.toString()+"/"+filename;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
//File sourceFile = root;
if (sourceFile.isFile()) {
try {
String upLoadServerUri =
"http://www.tucuenca.com/cspm/cargar_archivo.php";
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
//conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
//conn.setConnectTimeout (5000) ;
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE",
"multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("bill", sourceFileUri);
conn.setRequestMethod("POST");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;
name=\"bill\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math
.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,
bufferSize);
}
// send multipart form data necesssary after file
// data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn
.getResponseMessage();
if (serverResponseCode == 200) {
Log.i(TAG, "enviarArchivo: Cargar completa");
BufferedReader in=new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb= new StringBuffer("");
String line="";
while((line=in.readLine())!=null){
sb.append(line);
break;
}
resul=sb.toString();
in.close();
// showSuccessMessage("El servidor responde "+resul);
}else if(serverResponseCode==400){
Log.i(TAG, "enviarArchivo: error 400 "+resul);
// showSuccessMessage("Error en el servidor");
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
服务器用代码400回答我,请求错误,URL处于活动状态并且可以正常工作(http://www.tucuenca.com/cspm/cargar_archivo.php),我正在使用android 9在华为中进行测试。
我在等待您的评论。