01-25-2013 03:06 AM
I'm trying to upload .AMR file to my server. My code is as follows:
public byte[] send(byte[] fileBytes) throws Exception
{
String boundary = getBoundaryString();
String endBoundary = "\r\n--" + boundary + "--\r\n";
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty(HttpProtocolConstants.HEADER _ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
OutputStream dout = hc.openOutputStream();
dout.write(boundaryMessage.getBytes());
dout.write(this.postBytes);
dout.write(endBoundary.getBytes());
dout.close();
int ch;
is = hc.openInputStream(); //exception raised here
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
System.out.println("res loaded..");
}
else {
System.out.println("Unexpected response code: " + hc.getResponseCode());
hc.close();
return null;
}
}
catch(IOException e)
{
System.out.println("====IOException : "+e.getMessage()+" Class: "+e.getClass());
}
catch(Exception e1)
{
System.out.println("====Exception : "+e1.getMessage()+" Class: "+e1.getClass());
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
System.out.println("====Exception : "+e2.getMessage());
}
}
return res;
}
The line of code highlighted above raises a ConnectionClosedException. Can anybody tell me why and what I can do to overcome it? Thanks in advance.
Solved! Go to Solution.
01-25-2013 04:21 AM
You should check the response code before you try to open the input stream and only open the input stream when the response code is HttpConnection.HTTP_OK.
01-25-2013 04:51 AM
Thanks. Okay I have done that. Now it raises the same exception on line hc.getResponseCode();
01-25-2013 05:21 AM
This suggests the server is not accepting your request. See if you can find out what the server thinks is happening. Check your URL too.
01-25-2013 06:28 AM
Solved. Had some problem in my code. Thanks for helping me everytime Peter. Thanks a ton.![]()