问题
I have a url of a file "http://www.example.com/123.aes" ( it contains data of a mp3 file with morethan 2MB). Now i want to fetch the data from this url. When i tried http connection to get data, its showing an error - Requested entity too large. How to solve this problem ?. my code is given below -
try {
HttpConnection httpConn = (HttpConnection) Connector.open(httpURL, Connector.READ, true);
final int iResponseCode = httpConn.getResponseCode();
Dialog.alert(iResponseCode+"");
InputStream is = httpConn.openInputStream();
byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
String result = new String(data);
Dialog.alert(result);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/pictures/"+System.currentTimeMillis()+".mp3", Connector.READ_WRITE);
conn.create();
OutputStream out = conn.openOutputStream();
out.write(data);
out.flush();
out.close();
conn.close();
} catch (IOException e) {
Dialog.alert(e+"");
}
Also i want to save it as mp3 file in phone memory.
回答1:
Hope this will help you. Try following function:
public static String getPage(String url) {
String response = "";
try {
HttpConnection conn =
(HttpConnection)Connector.open(url,Connector.READ_WRITE);
InputStream input =conn.openInputStream();
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
while( -1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
response = raw.toString();
input.close();
}
catch(Exception e) {
Dialog.alert(e.toString());
}
return response;
}
An example call to this function,
getPage("yourUrl;deviceside=true;interface=wifi");
回答2:
Finally I got the answer -
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(httpURL);
HttpConnection httpConn = (HttpConnection) connDesc.getConnection();
try {
httpConn.setRequestMethod(HttpConnection.GET);
InputConnection inputConn = (InputConnection) httpConn;
InputStream is = inputConn.openInputStream();
byte[] data =IOUtilities.streamToBytes(is);
Dialog.alert(original.toString());
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/pictures/"+System.currentTimeMillis()+".mp3", Connector.READ_WRITE);
conn.create();
OutputStream out = conn.openOutputStream();
out.write(original);
out.flush();
out.close();
conn.close();
} catch (IOException e) {
Dialog.alert(e+"");
}
来源:https://stackoverflow.com/questions/13467348/get-data-from-url-in-blackberry