I'm developing my application on a Samsung Galaxy S which I've upgraded to Android 4.2. The application run normally on this device.
When I test it on a phone which is running Android 2.2, an exception occurs.
I check it again and again,I find that the problem happen after the application sends a UDP DatagramPacket.
The problem never happen when I comment the code referring to sending UDP DatagramPacket.
Could anyone please tell me what‘s the reason why? How to solve the problem?
Main method:
public static String getDataFromServerInPostMethod(String url,
String content) {
HttpURLConnection httpurlconnection = null;
String result = "";
try {
InputStream stream = null;
// String host = android.net.Proxy.getDefaultHost();
// if (host != null) {
// int port = android.net.Proxy.getDefaultPort();
// SocketAddress vAddress = new InetSocketAddress(host, port);
// java.net.Proxy vProxy = new java.net.Proxy(
// java.net.Proxy.Type.HTTP, vAddress);
// httpurlconnection = (HttpURLConnection) new URL(url)
// .openConnection(vProxy);
// } else {
// httpurlconnection = (HttpURLConnection) new URL(url)
// .openConnection();
// }
httpurlconnection = (HttpURLConnection) new URL(url)
.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
// httpurlconnection.setRequestProperty("Connection", "Keep-Alive");
httpurlconnection.setReadTimeout(TIMEOUT * 1000);
httpurlconnection.setConnectTimeout(TIMEOUT * 1000);
try {
httpurlconnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
httpurlconnection.connect();
MyLog.e(TAG, "getURL:" + httpurlconnection.getURL());
httpurlconnection.getOutputStream().write(content.getBytes());
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
stream = httpurlconnection.getInputStream();
result = SystemUtil.convertStreamToString(stream);
if (httpurlconnection.getResponseCode() == 200) {
MyLog.w(TAG,
"Responsed-->>getURL:" + httpurlconnection.getURL());
} else {
MyLog.e(TAG,
"not Responsed,ResponseCode:"
+ httpurlconnection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
}
return result;
}
Do you have this permission in your AndroidManifest.xml file?
<uses-permission android:name="android.permission.INTERNET" />
Related
So we're encountering a scenario where our Android clients are receiving a redirect from the server (following a POST -- Post/Redirect/Get) and Android is removing the body for the conversion to GET but seems to be leaving the Content-Length header in the GET request. I've verified that the request isn't making it into the web application (by placing a delegating handler that fires before a controller is selected). We also verified via cURL that if the content-length is removed from the request, the request goes through just fine.
So we're trying to find a solution on either front:
a) how do we stop android from sending that header? or
b) how do we tell IIS to allow or strip out the content-length header so that the request can get through?
UPDATE:
Requested java code that makes the call, as requested...
OutputStream postOut = null;
HttpURLConnection connection = null;
try {
URL url = new URL("<<url here>>");
connection = (HttpURLConnection) url.openConnection();
final String method = "POST";
final String data = "name=frank";
final String contentType = "application/x-www-form-urlencoded";
connection.setDoInput(true);
connection.setRequestProperty("Accept", contentType);
connection.setRequestProperty("Connection", "Close");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod(method);
connection.setConnectTimeout(0);
connection.setReadTimeout(0);
connection.setUseCaches(false);
connection.setDefaultUseCaches(false);
connection.setChunkedStreamingMode(0);
if (method.equals("POST")) {
byte[] bits = data.getBytes();
connection.addRequestProperty("Content-Length", "" + bits.length);
connection.setDoOutput(true);
dumpHeaders(connection.getRequestProperties());
postOut = connection.getOutputStream();
if (postOut != null)
{
postOut.write(bits, 0, bits.length);
postOut.flush();
postOut.close();
postOut = null;
}
} else {
dumpHeaders(connection.getRequestProperties());
}
int httpStatus = connection.getResponseCode();
if (httpStatus / 100 > 3) {
Log.d("TEST", readResponse(connection.getErrorStream(), connection));
} else {
Log.d("TEST", readResponse(connection.getInputStream(), connection));
}
String finalUrl = connection.getURL().toExternalForm();
Log.d("TEST", "HTTP Status: " + httpStatus + ", URL: " + finalUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
if (connection.getErrorStream() != null) {
Log.d("TEST", readResponse(connection.getErrorStream(), connection));
} else {
Log.d("TEST", e.getMessage());
}
}
if (connection != null) {
connection.disconnect();
}
I call the following function to get the total files size to download:
private Uri askForFileSizeFromURL(URL url, String fileName) {
try {
URLConnection conn = url.openConnection();
HttpURLConnection httpConnection = conn instanceof HttpURLConnection ? (HttpURLConnection ) conn : null;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
bytesToDownload += httpConnection.getContentLength();
return null;
}
}
catch(ConnectException e) {
Log.d("2ndGuide", "ConnectException." + e);
downloadAborted = true;
return null;
}
catch(IOException e)
{
Log.d("2ndGuide", "IO Exception." + e);
}
return null;
}
I'm calling this function 31 times and it takes more than 23 secondes. Without this call the loop takes 320ms. So the problem comes from this code.
Is there a quicker way to get files size from a remote server on Internet?
Regards,
Alain
So, I can't get rid of this problem:
I need to upload a XML file and a .jpg file from my android app(API 8) to a HTTP server (win 2008 server with IIS 7.5). I've already enabled PUT verbs and uninstalled WebDav & webdav methods as suggested from previous searches.
Plus, i'm not sure i'm doing it right server side because i can't get any response back.
here's my code
URL fileurl = new URL("Server Upload Path");
HttpURLConnection urlConnection = (HttpURLConnection) fileurl
.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.setDoOutput(true);
urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
File upFile = new File("My Local File");
//I'm sure the file exists
FileInputStream fis = new FileInputStream(upFile);
BufferedInputStream bfis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int bufferLength = 0;
// now, read through the input buffer and write the contents to the
// file
while ((bufferLength = bfis.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
Sorry if I forget some info you may need to help. I'm new to android and IIS too.
Why not try a standard multi-part file upload request (based on POST and not PUT):
final static String MULTIPART_BOUNDARY = "------------------563i2ndDfv2rTHiSsdfsdbouNdArYfORhxcvxcvefj3q2f";
public static void sendFileToServer(String url, File logFiles) {
HttpURLConnection connection = null;
OutputStream os = null;
DataInputStream is = null;
try {
StringBuilder fullUrl = new StringBuilder(url);
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MULTIPART_BOUNDARY);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
os = new BufferedOutputStream(connection.getOutputStream());
if(os != null) {
os.write(("--" + MULTIPART_BOUNDARY + EOL).getBytes());
os.write(String.format("Content-Disposition:form-data;name=\"UploadedFile\";filename=\"%s\"\r\nContent-Type: application/x-zip-compressed\r\n\r\n", UPLOADED_FILE_NAME).getBytes());
// Upload file(s) data here and send
os.write((EOL + "--" + MULTIPART_BOUNDARY + "--" + EOL + EOL).getBytes());
os.flush();
os.close();
os = null;
}
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Process server response
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e1) {
} finally {
try {
if(os != null) {
os.close();
}
} catch (IOException e) {
Log.e(TAG, "sendFileToServer exception: close OutputStream", e);
}
try {
if(is != null) {
is.close();
}
} catch (IOException e) {
Log.e(TAG, "sendFileToServer exception: close InputStream", e);
}
if(connection != null) {
connection.disconnect();
}
}
}
I want to print the InputStream in logcat(for testing/later I will use it), my current code is as follows.
#Override
protected Void doInBackground(Void... params) {
try {
InputStream in = null;
int response = -1;
URL url = new URL(
"http://any-website.com/search/users/sports+persons");
URLConnection conn = null;
HttpURLConnection httpConn = null;
conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
if (in != null) {
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
// TODO: print 'in' from here
}
in.close();
in = null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
But I am not able to do this, so please check the code and add/modify the code to do this.
String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
And in your code:
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
Log.e(TAG, convertStreamToString(in));
Your TAG should be a constant like:
public final String TAG = YourActivity.class.getSimpleName();
Then you would do something like:
Log.e(TAG, "You're message here:", e)
e is your error from print stack.
You also want to make sure you import the Log in the Android library.
Also, after looking at your code, you might want to surround your httpConnection() with try/catch statement, that way you can catch the error, and put it in your Log file. You have the Log printing if your stream has something, or isn't null, but you want to know if you don't have a connection, and that would give you a null value.
Hope that helps.
Just add this code to if(in != null):
byte[] reqBuffer = new byte[1024];
int reqLen = 1024;
int read = -1;
StringBuilder result = new StringBuilder();
try {
while ((read = is.read(reqBuffer, 0, reqLen)) >= 0)
result.append(new String(reqBuffer, 0, read));
} catch (IOException e) {
e.printStackTrace();
}
Log.d("TAG", result.toString());
I want to Download An image from a remote server. But each time I get A nullpointer exception.
Method For Conencting to Server
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.i("Download ", "Response: OK");
}
else
Log.i("Download ", "Response: NOK");
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
Method For Creating Bitmap
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
Log.i("Download ", "InputStream Available: " +in.available());
bitmap = BitmapFactory.decodeStream(in);
Log.i("Download ", "Bitmap: " +bitmap.describeContents());
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
The null pointerException is thrown when I decodeStream, but when I use a different URL it works.
I run Apache on port 90. could this also have an effect if any.
try this I hope is working.
to connect with ftp use this code
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
to download file use this code
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}