Right now i am working on Image download from web.For this i set http connection like below code.
HttpConnection connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
I am calling two images from web.for one picture it display image successfully.But for other picture it show error Unexpected response code:403.I am not understand why this problem is occur.How can i download image from web.Is there any change in HttpConnection need to modify.
Please help me.
Have you tested this on a real phone, or just in the emulator?
If you are using the emulator, make sure you've configured it to connect to the internet, it won't be configured to do that by default.
BlackBerry emulator not connecting to internet
Use this function , as we get bytes from the http connection,you need to convert those bytes into image this function will do that for you , just pass the url of the image in arguments:
public static Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
int currentWidthFixed32 = Fixed32.toFP(hai.getWidth());
int currentHeightFixed32 = Fixed32.toFP(hai.getHeight());
int reqWidth = 48;
int reqHeight = 35;
int requiredWidthFixed32 = Fixed32.toFP(reqWidth);
int requiredHeightFixed32 = Fixed32.toFP(reqHeight);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
hai = hai.scaleImage32(scaleXFixed32, scaleYFixed32);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" +url+ ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
Related
I'm developing an iOS app, using Codename One. I extended the SocketConnection class, in order to receive data from a server.
class CustomSocketConnection extends SocketConnection {
private OutputStream os;
private InputStream is;
private InputStreamReader isr;
private String rawMessage;
public CustomSocketConnection(){
os = null;
is = null;
isr = null;
rawMessage = null;
}
public synchronized String getRawMessage(){
return rawMessage;
}
#Override
public void connectionError(int errorCode, String message) {
rawMessage = null;
ToastBar.showErrorMessage("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
System.out.println(">>>CustomSocketConnection, connectionError. Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
System.out.println(">>>CustomSocketConnection, connectionEstablished");
char termination = '\n';
int length = 1024;
char[] buffer = new char[length];
byte[] bufferByte = new byte[length];
StringBuilder stringBuilder = new StringBuilder();
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima del while");
try {
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima della read");
while(true){
System.out.println(">>>CustomSocketConnection, loop di read, inizio");
int read = isr.read();
System.out.println(">>>CustomSocketConnection, loop di read, subito dopo la read");
char c = (char) read;
if (read == -1) rawMessage = null;
System.out.println(">>>CustomSocketConnection, loop di read, letto: " + c);
while(c != termination){
stringBuilder.append(c);
read = isr.read();
c = (char) read;
if (read == -1) rawMessage = null;
}
rawMessage = stringBuilder.toString();
if(rawMessage != null) doActions(rawMessage);
//System.out.println(">>>CustomSocketConnection, connectionEstablished, ho letto: " + rawMessage + "FINE");
}
}
catch (IOException ex) {
System.out.println(">>>CustomSocketConnection, connectionEstablished, errore: " + ex.getMessage());
}
System.out.println(">>>CustomSocketConnection, connectionEstablished, dopo il while");
}
private void doActions(String msg){
//do something
}
}
In the connectionEstablished method, I read data from server, using the read method of the InputStreamReader class.
If I run the app on the simulator, it works properly and it receives data from server. When I launch the app on real devices (iPad mini, 32-bit device, iOS version 8.1.1 12B435, more details here; iPhone 7s, 64-bit device, iOS version 11.2.5 15D60), the read method doesn't receive data from server. In fact, I can see the string printed by the println before the read method, but I can't see the string printed by the println after the read method.
The issue is not server-side, because I developed an Android app and it receive data from the same server. There aren't firewall restrictions or other network limitations: Android app and the Codename One simulator both receive data when connected on the same local network of the server or from another one.
What's wrong?
Solved using InputStream instead of InputStreamReader.
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
System.out.println(">>>CustomSocketConnection, connectionEstablished");
char termination = '\n';
StringBuilder stringBuilder = new StringBuilder();
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima del while");
try {
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima della read");
while(true){
System.out.println(">>>CustomSocketConnection, loop di read, inizio");
int read = is.read();
System.out.println(">>>CustomSocketConnection, loop di read, subito dopo la read");
char c = (char) read;
if (read == -1) rawMessage = null;
System.out.println(">>>CustomSocketConnection, loop di read, letto: " + c);
while(c != termination){
stringBuilder.append(c);
read = is.read();
c = (char) read;
if (read == -1) rawMessage = null;
}
rawMessage = stringBuilder.toString();
if(rawMessage != null) doActions(rawMessage);
//System.out.println(">>>CustomSocketConnection, connectionEstablished, ho letto: " + rawMessage + "FINE");
}
}
catch (IOException ex) {
System.out.println(">>>CustomSocketConnection, connectionEstablished, errore: " + ex.getMessage());
}
System.out.println(">>>CustomSocketConnection, connectionEstablished, dopo il while");
}
Can anyone explain me why it's working with InputStream?
I want to save many files on Sdcard. When I save these files on folder I get a warning that the memory is low
the device memory is too low - please close the following items
and the application crashed.
The problem that I can put the folder manually and I didn't get problem of memory but in the pplication it show it even there is free space on Sdcard.
This the method that I used to save files.
public static void saveWebContentCache(String save_name, String url) {
FileConnection fconn = null;
OutputStream outputStream = null;
try {
fconn = (FileConnection) Connector.open(
NetWorkConfig.webfolder + save_name,
Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
outputStream = fconn.openOutputStream();
outputStream.write(getByte(url));
}
} catch (IOException e) {
Status.show("ko !");
} finally {// Close the connections
try {
if (outputStream != null) {
outputStream.close();
outputStream = null;
}
} catch (Exception e) {
}
try {
if (fconn != null) {
fconn.close();
fconn = null;
}
} catch (Exception e) {
}
}
}
As for me, this line looks suspicious:
outputStream.write(getByte(url));
This is because such implementation implies you have to create/hold in RAM the entire byte array before writing it to file's OutputStream.
Instead, you could combine reading by small chunks from the InputSteam of an http connection and writing the chunks to file's OutputStream. Something like this:
void copyData(InputStream source, OutputStream destination) throws IOException {
byte[] buf = new byte[1024];
int len;
while ((len = source.read(buf)) > 0) {
destination.write(buf, 0, len);
}
destination.flush();
}
I am using this Utility
public class Util_ImageLoader {
public static Bitmap _bmap;
Util_ImageLoader(String url) {
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;
try {
connection = (HttpConnection) Connector.open(url + Util_GetInternet.getConnParam(), Connector.READ,
true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + responseCode);
}
final String result = rawResponse.toString();
dataArray = result.getBytes();
} catch (final Exception ex) {
}
finally {
try {
inputStream.close();
inputStream = null;
connection.close();
connection = null;
} catch (Exception e) {
}
}
bitmap = EncodedImage
.createEncodedImage(dataArray, 0, dataArray.length);
int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
multH = Fixed32.div(Fixed32.toFP(currHeight), Fixed32.toFP(currHeight));// height
multW = Fixed32.div(Fixed32.toFP(currWidth), Fixed32.toFP(currWidth));// width
bitmap = bitmap.scaleImage32(multW, multH);
_bmap = bitmap.getBitmap();
}
public Bitmap getbitmap() {
return _bmap;
}
}
When I call it in a listfield which contains 10 childs, then the log keeps saying failed to allocate timer 0: no slots left.
This means the memory is being used up and no more memory to allocate again and as a result my main screen cannot start.
At the same time you have the following objects in memory:
// A buffer of about 10KB
byte[] responseData = new byte[10000];
// A string buffer which will grow up to the total response size
rawResponse.append(new String(responseData, 0, length));
// Another string the same length that string buffer
final String result = rawResponse.toString();
// Now another buffer the same size of the response.
dataArray = result.getBytes();
It total, if you downloaded n ascii chars, you have simultaneously 10KB, plus 2*n bytes in the first unicode string buffer, plus 2*n bytes in the result string, plus n bytes in dataArray. If I'm not wrong, that sums up to 5n + 10k. There's room for optimization.
Some improvements would be:
Check response code first, and then read the stream if response code is HTTP 200. No need to read if server returned an error.
Get rid of strings. No need to convert to string if after that you are converting again to bytes.
If images are large, don't store them in RAM while downloading. Instead, open a FileOutputStream and write to a temporary file as you read from input stream. Then, if temporary images are still large enough to be displayed, downscale them.
I have an Image object which is a jpg picture taken by the camera and I need to create a Bitmap from it.
Is there any way to do it besides using BMPGenerator class? I'm working on a commercial project and I don't think I can use it due to the GPLv3 license.
So far this is the code I have. Can I do something with it?
FileConnection file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE);
InputStream is = file.openInputStream();
Image capturedImage = Image.createImage(is);
I tried this but I wasn't able to get the correct filepaht and the image is stuck in null
EncodedImage image = EncodedImage.getEncodedImageResource(filePath);
byte[] array = image.getData();
capturedBitmap = image.getBitmap();
You can use videoControl.getSnapshot(null) and then Bitmap myBitmap = Bitmap.createBitmapFromBytes(raw, 0, raw.length, 1) to get a bitmap from camera.
videoControl is got from player.getControl("VideoControl") and player is got from Manager.createPlayer()
By the way, what kind of Image do you have? If we are talking of EncodedImage, you can just use getBitmap() from it.
Fixed!
Well, almost.
Used the following method but the image is rotated 90 degrees.
Going to fix that with this
public Bitmap loadIconFromSDcard(String imgname){
FileConnection fcon = null;
Bitmap icon = null;
try {
fcon = (FileConnection)Connector.open(imgname, Connector.READ);
if(fcon.exists()) {
byte[] content = new byte[(int) fcon.fileSize()];
int readOffset = 0;
int readBytes = 0;
int bytesToRead = content.length - readOffset;
InputStream is = fcon.openInputStream();
while (bytesToRead > 0) {
readBytes = is.read(content, readOffset, bytesToRead);
if (readBytes < 0) {
break;
}
readOffset += readBytes;
bytesToRead -= readBytes;
}
is.close();
EncodedImage image = EncodedImage.createEncodedImage(content,0,content.length);
icon = image.getBitmap();
}
} catch (Exception e) {
}finally{
// Close the connections
try{ if(fcon != null) fcon.close(); }
catch(Exception e){}
}
return icon;
}
i am using the following code for establishing Https connection
HttpsConnection httpConnector = null;
InputStream in = null;
Document doc ;
String content = "";
try
{
httpConnector = (HttpsConnection)Connector.open(url,Connector.READ_WRITE);
httpConnector.setRequestMethod(HttpConnection.GET) ;
in = httpConnector.openInputStream();
byte[] data = new byte[in.available()];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while ( -1 != (len = in.read(data)) ) {
raw.append(new String(data, 0, len));
size += len;
}
content = raw.toString().trim();
}
catch(Exception ex)
{
ex.printStackTrace();
return false;
}
try{
in.close();
in =null;
httpConnector.close();
httpConnector =null;
}catch(Exception ex)
{
Dialog.alert("Error:" + ex.getMessage());
return false;
}
}
i think i am able to establish the connection but the values are not coming. i am testing it on Simulator, i have not tested on device
I think your mistake is in the following line:
byte[] data = new byte[in.available()];
The available() method only returns how many bytes are immediately available for reading from the inputstream, but you are using it to initialize the size of the temporary byte array. Since it's possible that available() returns 0, you may be initializing a zero-length array.
It would be better to just initialize "data" with a fixed-length array.