Java 无法将其他扩展名文件上载到web服务器

Java 无法将其他扩展名文件上载到web服务器,java,http,network-programming,content-type,httpurlconnection,Java,Http,Network Programming,Content Type,Httpurlconnection,我总是得到异常:java.io.IOException:服务器返回HTTP响应代码:400,用于URL:而不是txt。 这是我的密码 FileInputStream fis= new FileInputStream(filepath); byte[] buf = new byte[1024]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); for(int readnum; (readnum = fis.read(buf)) !

我总是得到异常:java.io.IOException:服务器返回HTTP响应代码:400,用于URL:而不是txt。 这是我的密码

FileInputStream fis= new FileInputStream(filepath);
byte[] buf = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();

for(int readnum; (readnum = fis.read(buf)) != -1; )
{
 bos.write(buf,0,readnum);
 System.out.println("read"+ readnum+ "bytes");  

}
byte[] bytes = bos.toByteArray();
String filemsg = new String(bytes,"cp1252");
filemsg = URLEncoder.encode(filemsg,"UTF-8");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
 //connection.setRequestProperty("Content-Type","multipart/form-data;    boundary=**************");         
connection.addRequestProperty("Content-Type","text/html;charset=utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(filemsg.length()));
connection.setRequestProperty("Content-Language", "en-US");   
connection.setRequestProperty("method","setmsg");
connection.setRequestProperty("sender",sender);
connection.setRequestProperty("recipent",recipent);
connection.setRequestProperty("msg",tf.getText());
connection.setRequestProperty("time",time.format(cal.getTime()));
connection.setRequestProperty("hms",hms.format(cal.getTime()));
connection.setRequestProperty("file",filemsg);
connection.setDoInput(true);
connection.setDoOutput(true);
wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes(" ");
wr.flush ();
wr.close ();   

tf.setText("");
is = connection.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
String line;
response = new StringBuffer(); 
while((line = rd.readLine()) != null) 
{
  response.append(line);
  response.append('\r');
}
System.out.println(response.toString());
rd.close();
tf.setText(""); 
tf.requestFocus(true);
}

我正试图向Web服务器发送一个.wav文件,但服务器将此异常作为响应。该代码适用于任何.txt文件,甚至是压缩(.rar)格式的.txt文件。我猜“内容类型”部分出现了一些问题,但我不确定……谢谢您的帮助。

有很多HTTP API不需要您进行这种低级编码,希望它们能够避免您当前破坏二进制数据的方式。我建议你使用其中的一个——例如,查看Apache HTTP客户端库。请发布准确的错误消息事实上,此模块是我大学项目的一部分,因此我不能使用第三方API进行此操作……我需要找到一种方法,仅使用此方法上载其他扩展文件……谢谢你的建议