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());
Related
I'm using Asynctask to pass the parameters of API. The Asynctask executing but the String Response in Asynctask PostExecute giving me a null for a device with SDK 23 and below. But when the device is equal or higher to SDK24(Nougat), it works perfectly and the data are being sent to the API however when the SDK is 23 and lower data are not being sent to API. Does anyone encounter this problem? Please enlighten me what I miss in my code or I do wrong code. Massive thank you.
private class sendToServerOfficial extends AsyncTask<String,Void,String> {
int statusCodeone;
String convert_txt_et_username = et_username.getText().toString();
String convert_txt_content = et_content.getText().toString();
#Override
protected String doInBackground(String... strings) {
try {
urlURL = new URL("http://www.testingsite.com/api/sendServer?/ip="+getIPAddress+"&phone_num="+getMobilePhoneNumber+"&user_text="+convert_txt_et_username+"&content_text="+convert_txt_content);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlURL.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","UTF-8");
httpURLConnection.connect();
statusCodeone = httpURLConnection.getResponseCode();
if (statusCodeone == 200) {
InputStream it = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
buff.close();
read.close();
return dta.toString();
}
}
catch (ProtocolException e) { e.printStackTrace(); }
catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return null;
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(MainActivity.this, response + "Form is submitted already" + urlURL, Toast.LENGTH_LONG).show();
txt_inputURL.setEnabled(true);
btnClick.setClickable(true);
txt_inputURL.getText().clear();
}
}
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
I was previously using HttpClient and BasicNameValuePairs, for some reason i have to shift to HttpUrlConnection.
Hence this code, to make a HttpPost request with certain parameters:
public class MConnections {
static String BaseURL = "http://www.xxxxxxxxx.com";
static String charset = "UTF-8";
private static String result;
private static StringBuilder sb;
private static List<String> cookies = new ArrayList<String>();
public static String PostData(String url, String sa[][]) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(BaseURL + url)
.openConnection();
} catch (MalformedURLException e1) {
} catch (IOException e1) {
}
cookies = connection.getHeaderFields().get("Set-Cookie");
try{
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
}catch (Exception e) {
//Here i get Exception that "java.lang.IllegalStateException: Already connected"
}
OutputStream output = null;
String query = "";
int n = sa.length;
for (int i = 0; i < n; i++) {
try {
query = query + sa[i][0] + "="
+ URLEncoder.encode(sa[i][1], "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (Exception e) {
//Here i get Exception that "android: java.net.protocolException: Does not support output"
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
}
}
InputStream response = null;
try {
response = connection.getInputStream();
} catch (IOException e) {
//Here i get Exception that "java.io.IOException: BufferedInputStream is closed"
} finally {
//But i am closing it here
connection.disconnect();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
response, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append("\n" + line);
}
response.close();
result = sb.toString();
} catch (Exception e) {
}
return result;
}
}
But i get such Exceptions as commented in the code.
Actually i am calling MConnections.PostData() twice from my Activity using a AsyncTask. This might cause the Exception: Already Connected but i am using connection.disconnect. But why am i still getting that Exception?
Am i using it the wrong way?
Thank You
For the protocol exception, try adding the following before you call getOutputStream():
connection.setDoOutput(true);
Discovered this answer thanks to Brian Roach's answer here: https://stackoverflow.com/a/14026377/387781
Side note: I was having this issue on my HTC Thunderbolt running Gingerbread, but not on my Nexus 4 running Jelly Bean.
I have this code from a book I have to learn about Android .. what's wrong?
I always get 01 Error Connecting which is an exception in my code while establishing http connection.
public class HttpImgActivity extends Activity {
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null; // creating My input
int response = -1;
URL url= new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) // if not a valid URL
throw new IOException ("NOT an Http connection");
try{
HttpURLConnection httpconn = (HttpURLConnection) conn;
httpconn.setAllowUserInteraction(false); // prevent user interaction
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect(); //initiates the connection after setting the connection properties
response = httpconn.getResponseCode(); // getting the server response
if(response == HttpURLConnection.HTTP_OK ) // if the server response is OK then we start receiving input stream
{ in = httpconn.getInputStream(); }
} // end of try
catch(Exception ex)
{
throw new IOException(" 01 Error Connecting");
}
return in; // would be null if there is a connection error
} // end of my OpenHttpConnection user defined method
*/
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap= null;
InputStream in = null;
try
{
in = getInputStreamFromUrl(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1)
{
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
return bitmap; // this method returns the bitmap which is actually the image itself
}
ImageView img;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.egyphone.com/wp-content/uploads/2011/05/Samsung_Galaxy_S_II_2.jpg");
img =(ImageView) findViewById(R.id.myImg);
img.setImageBitmap(bitmap);
}
}
Any ideas?
It seems you catch your exception, but you don't use it for anything.
Try changing throw new IOException(" 01 Error Connecting"); to throw new IOException(ex.toString());
And you should think about using Android's logging tools, instead to see your errors through logcat:
...
catch(Exception ex)
{
Log.e("CONNECTION", ex.toString(), ex);
}
...
This makes debugging easier IMO.
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;
}