我正在尝试将 UTF-8 文本文件上传到 Blackberry 中的服务器。上传效果很好,但是当我检查服务器中的文件时,它是一个 ASCII 文件,而我需要的是一个 UTF-8 文件。
这是我在创建文件时使用的代码:
FileConnection fc = (FileConnection)Connector.open(fileName);
if (!fc.exists()){
fc.create();
}
long byteOffset = fc.usedSize();
OutputStream outStream = fc.openOutputStream(byteOffset);
outStream.write(line.getBytes("UTF-8"));
outStream.close();
fc.close();
要发送文件,我使用这个:
public void run (){
httpConnection = null;
_connectionURL = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int rc = -1;
OutputStream os = null;
try {
_connectionURL = Constants.UPLOAD_URL + getConnectionString();
httpConnection = (HttpConnection)Connector.open(_connectionURL);
byte [] postDataBytes = getData();
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Connection", "Keep-Alive");
httpConnection.setRequestProperty("User-Agent", "BlackBerry");
httpConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
httpConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");
httpConnection.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
os = httpConnection.openOutputStream();
os.write((twoHyphens + boundary + lineEnd).getBytes());
os.write(("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName +"\"" + lineEnd).getBytes());
os.write(lineEnd.getBytes());
os.write(postDataBytes);
os.write(lineEnd.getBytes());
os.write((twoHyphens + boundary + twoHyphens + lineEnd).getBytes());
os.flush();
// Response
rc = httpConnection.getResponseCode();
InputStream in = httpConnection.openInputStream();
int ch;
StringBuffer stringBuffer = new StringBuffer();
while( ( ch = in.read() ) != -1 ){
stringBuffer.append( (char)ch );
}
String responseString = stringBuffer.toString();
...
}catch (IOException ioe){
...
}
}
...
private byte[] getData() throws IOException {
int _c;
StringBuffer _stringBuffer = new StringBuffer("UTF-8");
FileConnection fileForUpload = (FileConnection) Connector.open(Constants.FOLDER_FILES+this.fileName, Connector.READ);
this.fileInputStream = fileForUpload.openDataInputStream();
this.postData = new URLEncodedPostData("UTF-8", false);
while( (_c = this.fileInputStream.read()) != -1){
_stringBuffer.append((char)_c);
}
postData.setData(_stringBuffer);
byte [] _postData = postData.getBytes();
fileForUpload.close();
return _postData;
}
我猜getData()方法或httpConnection属性有问题,但我不知道是什么问题。
谢谢你的帮助