0

我总是遇到异常:java.io.IOException:服务器返回 HTTP 响应代码:URL 为 400:对于 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);
}

我正在尝试将 .wav 文件发送到网络服务器,但我收到此异常作为来自服务器的响应。该代码适用于任何 .txt 甚至 .txt 文件的压缩 (.rar) 形式。我猜“内容类型”部分有一些问题,但我不确定......感谢您的帮助。

4

0 回答 0