Sending data via post without using apache classes - android

I want to send data to a php server without using http classes if this is possible; ie the org.apache.http package.
My code until now
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class serverHandler extends AsyncTask<String,Integer,String> {
Context context;
ByteArrayOutputStream content;
public serverHandler(Context context){
this.context = context;
}
#Override
protected String doInBackground(String... params) {
InputStream input = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
byte buff[] = new byte[4096];
content = new ByteArrayOutputStream();
long total = 0;
int count;
while ((count = input.read(buff)) != -1) {
// allow canceling with back button
content.write(buff,0,count);
total += count;
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return new String(content.toByteArray());
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String country = "No Country";
if(result.length()==0){
Toast.makeText(context, "No Data", Toast.LENGTH_LONG).show();
return;
}
try{
JSONObject data = new JSONObject(result);
JSONObject address = data.getJSONObject("address");
country = address.getString("country");
}
catch(JSONException e){
e.printStackTrace();
}
Toast.makeText(context,country,Toast.LENGTH_LONG).show();
}
}
I know that sending POST data for sure will need some HTTP service. What I'm asking for is if it's possible to send the data without importing any of the org.apache.http packages. All the SO answers and the examples I found on the internet are using this package. And I, for some reason, don't want to use it if this is possible.

You can use square's retrofit library for POST data to server.

Related

How to resolve android.os.networkonmainthreadexception

I am new to android and I am trying to read data from a server. I use a util and call that util like this
private void ParseSource(String Url){
String source = new Cls_SourceGrabber().grabSource(Url);
}
But I am getting a android.os.networkonmainthreadexception. How can I reduce that?
My SourceGrabber util:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Cls_SourceGrabber {
private HttpGet mRequest;
private HttpClient mClient;
private BufferedReader mReader;
private StringBuffer mBuffer;
private String mNewLine;
public Cls_SourceGrabber() {
mRequest = new HttpGet();
InitializeClient();
mReader = null;
mBuffer = new StringBuffer(10000);
mNewLine = System.getProperty("line.separator");
}
private void InitializeClient() {
if (mClient == null || mClient.getConnectionManager() == null) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4500);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
// HttpConnectionParams.setTcpNoDelay(httpParameters, true);
mClient = new DefaultHttpClient(httpParameters);
}
}
/*
*Grab the full source
*/
public String grabSource(String url) {
mBuffer.setLength(0);
InitializeClient();
String source = "";
try {
mRequest.setURI(new URI(url));
HttpResponse response = mClient.execute(mRequest);
mReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = mReader.readLine()) != null) {
mBuffer.append(line);
mBuffer.append(mNewLine);
source = mBuffer.toString();
if (Thread.interrupted()) {
break;
}
}
} catch (ConnectTimeoutException e) {
source = "Connection Timed Out.";
} catch (java.net.UnknownHostException e) {
source = "No Internet Connection available!";
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
source = "Site Parsing Exception.";
} catch (ClientProtocolException e) {
source = "Protocol Exception.";
} catch (IOException e) {
source = "Server not responding.";
} catch (URISyntaxException e) {
source = "Wrong URL!";
} catch (Exception e) {
source = "Exception - " + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
closeReader();
}
return source;
}
}
First of all, I would not recommend on using HTTPClient any more, since it is not supported any more from sdk version 23.
So, it will be better to migrate the network operations to URL Connection.
Now, android never allows network operations on Main thread since it will block the UI thread for a considerable time, hence may cause crash or bad user experience.
You can take a look on these docs : Doc 1
The better way to do Network operations is by creating an AsyncTask.
Just take care not to access any UI thread element in the doInBackground method. You can modify UI Thread elements on onPreExecute or onPostExecute Methods.
I have created a NetworkOps Util. You can take a look on that, whether it may be any use for you :
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains("~Exception~")) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

Load a JSON file stored online

Is there an easy way to point the code below to a URL that has JSON data. Before I had the following with my Json file in the Assets folder:
InputStream is = context.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
What is in that data.json file is now stored online. If I get the string of that URL as String URL = "http...whatever....data.json" how do I initialize the InputStream in the first line of code?
That code is specific to reading from files. You will need to setup an AsyncTask and pull the data in a background thread.
This page explains the issues and provides good examples.
http://developer.android.com/training/basics/network-ops/connecting.html
Update 1:
Here is code from a project that pulls the data and parses it and populates a java object:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.google.gson.Gson;
public class RestServices
{
public static String getServerAddress()
{
return "http://192.168.96.179:8090/";
}
public static String getRestURI()
{
return "api/";
}
public static <T> T getExternalData(Class<T> clazz, String uri) throws IOException
{
String responseString = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
String address = getServerAddress() + getRestURI() + uri;
HttpResponse response = httpclient.execute(new HttpGet(address));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
catch (ClientProtocolException e)
{
}
Gson gson = new Gson();
T object = gson.fromJson(responseString, clazz);
return object;
}
}
And how I call it:
class SiteConfigTask extends AsyncTask<Void, SiteConfig, SiteConfig>
{
#Override
protected SiteConfig doInBackground(Void... none)
{
SiteConfig sc = null;
try
{
sc = RestServices.getExternalData(SiteConfig.class, "siteconfig");
} catch (IOException e)
{
Log.e(TAG,"Failed to fetch siteconfig", e);
}
return sc;
}
#Override
protected void onPostExecute(SiteConfig result)
{
super.onPostExecute(result);
if ( result == null )
{
EventBus.getDefault().post(new ConfigurationFetchErrorEvent());
}
else
{
// Adds an additional empty stream if there are
// and odd number of streams, the new stream will be disabled.
if ( result.getStreamList().size() % 2 != 0)
{
Stream s = new Stream();
s.setEnabled(false);
result.getStreamList().add(s);
}
updateSiteConfig(result);
}
}
}
You could request the resource via HttpURLConnection like the code snippet below.
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL("http://www.example.com/data.json");
connection = (HttpURLConnection) url.openConnection();
inputStream = connection.getInputStream();
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Android applications can't upload photos to the server

I want to do an App. It can realize to upload the phone picture to server. Now it can take the picture and save to the mobile phone. But it can not upload into server. How to deal with this? The server is using tomcat to setup.
Android upload code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class uploadActivity extends Activity
{
private Button uploadbutton;
private String uploadFile = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String srcPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String actionUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
uploadbutton=(Button)findViewById(R.id.button2);
uploadbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
private void uploadFile()
{ String uploadUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
Toast.makeText(this, result, Toast.LENGTH_LONG).show();//
dos.close();
is.close();
} catch (Exception e)
{
e.printStackTrace();
setTitle(e.getMessage());
}
}
}
The server code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CameraServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out2 = response.getWriter();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String uploadPath = "d:\\cameraupload\\";
File file = new File(uploadPath);
if (!file.exists())
{
file.mkdir();
}
String filename = "";
InputStream is = null;
for (FileItem item : items)
{
if (item.isFormField())
{
if (item.getFieldName().equals("filename"))
{
if (!item.getString().equals(""))
filename = item.getString("UTF-8");
}
}
else if (item.getName() != null && !item.getName().equals(""))
{
filename = item.getName().substring(
item.getName().lastIndexOf("\\") + 1);
is = item.getInputStream(); // 得到上传文件的InputStream对象
}
}
filename = uploadPath + filename;
if (new File(filename).exists())
{
new File(filename).delete();
}
// Began to upload files
if (!filename.equals(""))
{
// use FileOutputStream to open the upload file in server
FileOutputStream fos2 = new FileOutputStream(filename);
byte[] buffer = new byte[8192];
int count = 0;
// Began to read the upload file in bytes,and input it to server's upload file output stream
while ((count = is.read(buffer)) > 0)
{
fos2.write(buffer, 0, count); // To write the byte stream server files
}
fos2.close(); // close FileOutputStream object
is.close(); // InputStream object
out2.println("file upload success!xii");
}
}
catch (Exception e)
{
}
}
}
Do you have any error tracing?? Our just happening nothing??
For using httpurlconnection, you need to change the policy at the beginning:
ThreadPolicy mThreadPolicy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(mThreadPolicy);
Try this.
Isn't 192.168.1.105 an IP-adress on the local network? Are you sure it's reachable from your phone? Open your phone's browser and try to navigate to the URL, can you reach it?
At what end are you having problems with the upload? Client or server? If it's on the client, what error are you getting? Or is it silently failing? Have you tried to make a simple HTML form and do the upload from there? If that is working you know it's your Android code that is the problem?
Also, it hurts every time I see someone trying to implement file uploads on their own. I'm not saying that your code is wrong, but it's an awful lot of lines of code (thus more risk of errors) compared to if you'd use a 3rd party library to abstract away all of that code for you. A well known and popular library such as Android Asynchronous Http Client has good support for file uploads out of the box:
AsyncHttpClient client = new AsyncHttpClient();
String filename = "file.png";
File myFile = new File("/path/to/" + filename);
RequestParams params = new RequestParams();
try {
params.put("file", myFile);
params.put("filename", filename);
client.post("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet", params, responseHandler);
}
catch(FileNotFoundException e) {
// handle
}
Try this...add apache-mime4j-0.6.jar and httpmime-4.0.3.jar libs
File f=new File(exsistingFileName);
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet");
MultipartEntity Mentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String url1=exsistingFileName;
String mime;
String extension = MimeTypeMap.getFileExtensionFromUrl(url1);
if (extension != ""&&extension!=null) {
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(extension);
}
else
{
String ext = url1.substring((url1.lastIndexOf(".") + 1), url1.length());
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(ext);
}
ContentBody cbFile;
if(mime!=null)
cbFile= new FileBody(f,mime);
else
cbFile=new FileBody(f);
Mentity.addPart("file",cbFile);
post.setEntity(Mentity);
HttpResponse response = null;
try {
response = http.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
responseString = new BasicResponseHandler().
handleResponse(response);
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}

Basic android http get

I'm a android noob on programming, but with some help of a few programms I can learn the basics. I would like to do a basic http get request to an arduino ethernetshield.
For this I've found some code, but I can't get it to work.
I'm allways stuck on the getResponse part with the code I've tried from several pages.
I've found the following page which gave me readable code:
How to work with an image using url in android?
Now I've created the following:
Press on a button and do a get to an url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
Where can I find information to learn how to write the code correctly?
Or do you happen to have the answer in some kind of hint so I can learn from it?
You must create a BufferedReader passing the InputStream, then you can read strings
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then I recommend you make the connection (or read/write file) with a separeted thread from the Thread UI (use Thread, AsyncTask, Handler, etc) because that will improve your app.
http://developer.android.com/intl/es/guide/components/processes-and-threads.html

Why is the output shown for so less duration?

Can you please tell why the the output disappears so quickly?
If you want to run the code, you will need the following in your Androidmanifest.xml file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Below is the code:
package prototype.networking.textfiles;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity
{
//-------------------------------------------------------------- OpenHttpConnection()------------------------------------------------//
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();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
//--------------------------------------------------OpenHttpConnection ends here-------------------------------------------------------------//
//--------------------------------------------------Download Plain Text Files (RSS) --------------------------------------------------------------//
private String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try
{
in = OpenHttpConnection(URL);
}
catch (IOException e1)
{
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG) .show();
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try
{
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
}
catch (IOException e)
{
Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG) .show();
e.printStackTrace();
return "";
}
return str;
}
//-------------------------------------------------DownloadText() ends here--------------------------------------------------------------------------//
//-------------------------This method downloads "PLAIN TEXT FILES"-------------------------------------------------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String str = DownloadText("http://www.appleinsider.com/appleinsider.rss");
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG) .show();
}
}
You say "the output vanishes within a secon". But you show it in a Toast. And that is what a Toast is supposed to do: check out the documentation - "The notification automatically fades in and out, and does not accept interaction events". It is the desired functionality, not an issue.
The length of a Toast is either Toast.LENGTH_SHORT or Toast.LENGTH_LONG. If you want to show a notification for a longer period of time consider using custom Dialog or DialogFragment or StatusBarNotification. Or if you don't want it to disappear, simply put it inside a View, e.g. TextView.

Categories

Resources