When i call the http, and during it connection is cutt of..my app crashes.. how can i handle such issue in this code?
This also happens when there is no connection, and the http is called.. also it happens when i returns wrong format ( not json)..
HttpConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
// construct the URL
String serverURL = "xxxxxxxxxxxxxxxxxxxxxxx"+Common.getConnectionType();
// encode the parameters
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
byte[] postDataBytes = postData.getBytes();
// construct the connection
conn = (HttpConnection)Connector.open(serverURL, Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent", "BlackBerry/" + DeviceInfo.getDeviceName() + " Software/" + DeviceInfo.getSoftwareVersion() + " Platform/" + DeviceInfo.getPlatformVersion());
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", new Integer(postDataBytes.length).toString());
// write the parameters
os = conn.openOutputStream();
os.write(postDataBytes);
// write the data and get the response code
int rc = conn.getResponseCode();
if(rc == HttpConnection.HTTP_OK) {
// read the response
ByteVector buffer = new ByteVector();
is = conn.openInputStream();
long len = conn.getLength();
int ch = 0;
// read content-length or until connection is closed
if( len != -1) {
for(int i =0 ; i < len ; i++ ) {
if((ch = is.read()) != -1) {
buffer.addElement((byte)ch);
}
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
buffer.addElement((byte)ch);
}
}
// set the response
accountsResponse = new String(buffer.getArray(), "UTF-8");
} else {
accountsResponse = null;
}
} catch(Exception e){
accountsResponse = null;
} finally {
try {
os.close();
} catch (Exception e) {
// handled by OS
}
try {
is.close();
} catch (Exception e) {
// handled by OS
}
try {
conn.close();
} catch (Exception e) {
// handled by OS
}
}
Related
I have many images in a folder, and I want to upload this files, in that folder, to a php server, in java using httpurlconnection.
Until now, I made it but just with one photo, like the code I show you down.
public class SendImage {
private final String CrLf = "\r\n";
public static void main(String[] args) {
SendImage image = new SendImage();
image.httpConn();
}
private void httpConn(){
URLConnection lig = null;
OutputStream os = null;
InputStream is = null;
try{
String urlParameters = "subPasta=sandro&nomepc=Sandro-PC&printPasta=Printscreens";;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL("http://192.168.0.105/dashboard3/uploadImg.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
System.out.println("url: "+ url);
lig = url.openConnection();
lig.setDoOutput(true);
FileInputStream imgIs = new FileInputStream(new File("C:\\Users\\Sandro\\workspace\\testeLogin\\screenshot\\2017_3_16_3_59.png"));
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.png\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
lig.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
lig.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = lig.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = lig.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
}
But I want send all photos in that folder
if you can, show me the code in php too please.
Code:
String recipeName = this.recipe.getName().replace(" ", "%20");;
String recipeIngredients = this.recipe.getIngredients().replace(" ", "%20");;
String recipeInstructions = this.recipe.getInstructions().replace(" ", "%20");;
String recipeUserName = this.recipe.getUserName().replace(" ", "%20");;
int recipeRate = this.recipe.getRate();
int recipeAmountOfRate = this.recipe.getAmountOfRates();
String link = "http://***My_Site***/createRecipe.php?recipeName="+recipeName+"&recipeIngredients="+recipeIngredients
+"&recipeInstructions="+recipeInstructions+"&recipeUserName="+recipeUserName+"&recipeRate="+recipeRate+
"&recipeAmountOfRate="+recipeAmountOfRate;
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setChunkedStreamingMode(0);
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = in.read()) != -1) {
sb.append((char) ch);
}
Log.e("Error", sb.toString());
} catch(Exception e) {
Log.e("Error", e.toString());
} finally {
urlConnection.disconnect();
}
}
But i get the error:
E/Error: java.io.EOFException
Why is that?
in previous requests the request went good.
Doed the URL request too long?
Getting error on the return line and also not sure if the checking for the size is right.
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
if (szRead > 0) {
bufOut = Arrays.copyOf(buf, szRead);
}
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
The part:
if (szRead > 0) {
bufOut = Arrays.copyOf(buf, szRead);
}
Not sure if this is the right way to check it in java and also when doing this i'm getting error on the variable bufOut might not be init in this line:
return bufOut;
Why don't you try returning the value returned by Arrays.copyOf() rather than store it in a variable and then return it.
You get the possibly not initialised error because if szRead is zero or less, bufOut is not initialised. According to the specification, if szRead is negative (for example, if the file is at EOF when calling read()), it will throw an exception, so you could do either:
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
And catch the NegativeArraySizeException, or throw another AndroidRuntimeException for szRead < 0, or just do:
bufOut = Arrays.copyOf(buf, szRead < 0 ? 0 : szRead);
Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)
private final class ServerConnectThread2 extends Thread
{
private InputStreamReader _in=null;
private OutputStreamWriter _out=null;
private String _url;
private int _delay;
private String _key;
private String _connectionParameters;
OutputStream os=null;
FileConnection fconn=null;
ServerConnectThread2()
{
_key="";
}
public void run()
{
// check internet connection available
setConnectionStringParameter();
bulkUploaderFlag=true;
HttpConnection connection = null;
try
{
_url="http://xxx/bulkuploader.jsp";
_url= EncodeURL (_url) ;
_url = _url + _connectionParameters;
URLEncodedPostData _postData = new URLEncodedPostData("",false);
_postData.append("totalRecord",""+totalRecord);
int count=0;
while( count < totalRecord)
{
_postData.append("accountID"+count,"C"+(String)accountIDVector.elementAt(count));
_postData.append("deviceID"+count,(String)deviceIDVector.elementAt(count));
_postData.append("timestamp"+count,(String)timestampVector.elementAt(count));
_postData.append("statusCode"+count,(String)statusCodeVector.elementAt(count));
_postData.append("latitude"+count,(String)latitudeVector.elementAt(count));
_postData.append("longitude"+count,(String)longitudeVector.elementAt(count));
_postData.append("gpsAge"+count,(String)gpsAgeVector.elementAt(count));
_postData.append("speedKPH"+count,(String)speedKPHVector.elementAt(count));
_postData.append("heading"+count,(String)headingVector.elementAt(count));
_postData.append("altitude"+count,(String)altitudeVector.elementAt(count));
_postData.append("transportID"+count,(String)transportIDVector.elementAt(count));
//_postData.append("inputMask",""+0);
count++;
}
byte [] postDataBytes = _postData.getBytes();
// Open the connection
connection = (HttpConnection)Connector.open(_url, Connector.READ_WRITE, false);
// Set the request method as GET
connection.setRequestMethod("POST");
//connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//connection.setRequestProperty("Content-Type","application/octet-stream");
//connection.setRequestProperty("Content-Type","multipart/form-data");
String len =new String(postDataBytes);
System.out.println(len);
connection.setRequestProperty("Content-Length",""+len.length());
os= connection.openOutputStream();
os.write(postDataBytes);
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2 ]");
int rc = connection.getResponseCode();
if(rc == HttpConnection.HTTP_OK)
{
_in = new InputStreamReader(connection.openInputStream());
// Wait for an acknowledgment, in this case an '1' character, for 'Received'.
//char c = (char)_in.read();
int length=0;
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, http==OK ]\n");
StringBuffer buf = new StringBuffer();
while ((length = _in.read()) != -1) {
char c = (char)length;
buf.append(c);
if(c=='0')
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, c==0,not send in bulk unsucessfully ]\n");
System.out.println("DATA not send in bulk SUCCESSFULLY sct2, c==0");
break;
}
if(c=='1')
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, c==1, send in bulk successfully ]\n");
System.out.println("DATA send in bulk SUCCESSFULLY sct2");
String fullPath = "file:///SDCard/dataLog.txt";
try
{
fconn = (FileConnection) Connector.open(fullPath, Connector.READ_WRITE);
if (fconn.exists())
fconn.delete();
}
catch(Exception e){}
finally
{
if(fconn!=null)
fconn.close();
}
break;
}
}
}
else
{
System.out.println("DATA not send in bulk SUCCESSFULLY sct2");
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, http not ok ]\n");
}
}
catch (Exception e)
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, exception catch ]\n");
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() + ", "+e.getMessage()+" ] \n");
System.out.println("DATA not send in bulk SUCCESSFULLY"+e.getMessage());
}
finally
{
try
{
if(_in!=null)
_in.close();
if(_out!=null)
_out.close();
if(os!=null)
os.close();
if(connection!=null)
connection.close();
bulkUploaderFlag=false;
}
catch (IOException ioe)
{
// Do Nothing
}
return;
}
}
I think , you must call "dos.flush()" method. My code runs perfectly, postContent is string buffer and contanins 300KB string.
if (getPostContent() == null) {
httpConnection.setRequestMethod(HttpConnection.GET);
} else {
String type = "application/x-www-form-urlencoded";
byte[] bytes = postContent.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Type", type);
httpConnection.setRequestProperty("Content-Length", bytes.length + "");
httpConnection.setRequestMethod(HttpConnection.POST); //setupPost method for this conn
DataOutputStream dos = new DataOutputStream(httpConnection.openOutputStream());
dos.write(bytes);
dos.flush();
dos.close();
}