Read Buffered stream website and open the first result Android - android

I have the following code to read a website. The code is searches on google. I want to open automatically the first result and read it again. For the keywords i want the "I am feeling lucky is not working". Please somebody help me find a solution
I have the following code.
URL url = new URL("http://www.google.com/search?q=sample");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
readStream(in);
finally {
in.close();
}
}
The query sample is just a sample....

Its already discussed in SO QA :
How to search in google by using java code?
Your approach is also a solution. But it will be complex as it requires parsing of returned HTML.
I think there are some APIS for doing this.
http://code.google.com/p/google-api-java-client/
This is deprecated but might still work -->
http://code.google.com/apis/websearch/docs/

Related

Why is the example from developer.android not working

I'm about to code an Android app (using A.Studio 3.5.1) that should connect to a back-end using https. I'm quite new to the techniques so I looked at https://developer.android.com/training/articles/security-ssl.html#HttpsExample
I has four lines of code:
URL url = new URL("https://wikipedia.org");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);
When I try it I get a red text;
new URL gives MalformedURLException
url.openConnection() gives IOException,
urlConnection.getInputStream() also
copyInputStreamToOutputStream is not found.
I have read about copyInputStreamToOutputStream, that it can be solved
copyInputStreamToOutputStream(in, System.out)
and
Easy way to write contents of a Java InputStream to an OutputStream
I tried the first way, using apache commons, with no success.
I'm mostly curious about the exceptions.
I will try another walk-through on
https://codelabs.developers.google.com/codelabs/android-network-security-config/
But it would be nice to learn about this...
I have faced similar situations many times. This occur because the webpage you are trying to reach doesn't return anything as a response after connection is established. So the parsing returns IOException as there is nothing to read in the response of URL after connection.
newURL is returning MalformedURLException because your url contains -- " -- which should be escaped as these are special characters.
Hope this helps.

how can i get the content of the url below using HttpURLConnection for my android application

here is url ...
https://api.thingspeak.com/update?api_key=R3LQP7IXIXEQ1OIV&field1=0
Actually..I don't want to get the content of url.
I just want to update the value of field1 to 1 and 0.
If I just type this url in any broswer,my thingspeak data will be update.All I need to do is to write code like typing in any broswer of this url.
In that way I think I can turn on and off my led through android application for my IOT project.I think all I need to do is to make connection between apk and thingspeak from this url.I am new to android studio.I have tried many ways.Help me please.
Thanks a lot.
You can simply use a HTTP GET method (that is what your browser does).
To answer your question:
try {
// create the HttpURLConnection
url = new URL(yourUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here like your browser would
connection.setRequestMethod("GET");
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
connection.disconnect();
}
There are better (cleaner) ways to do his, but this should answers your question.
PS: Be aware that in Android you will not be able to do this on the main thread! You should do this in a AsyncTask, AsyncTaskLoader, ...

Searching for code to log raw HTTP+cookies from Android HttpURLConnection

Has anyone released code to show the full HTTP request/response headers, any intermediate redirects, and any cookie data for the Android HttpURLConnection? This would be similar to Firefox Web Console
I roughly know how to write this myself, but 1) it's a non-trivial amount of code 2) it's tricky to get this kind of code to work in all instances. So i'm interested in finding a readymade solution. I know how to tcpdump the emulator, but I'm searching for code to print this information into the Android Log class for really quick runtime debugging.
for header fields
URL url = new URL(str_url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.setConnectTimeout(TIMEOUT_SOCKET);
conection.setReadTimeout(TIMEOUT_CONNECTION);
conection.addRequestProperty("Accept-Encoding", "gzip");
RedirectLocations locations = new RedirectLocations();
// here u get all header fields and properties write it in logs
conection.getHeaderFields();
conection.getRequestProperties();
// conection.getOutputStream().write(buffer);
// download the file
InputStream is = conection.getInputStream();
// This is file path were a; quiz data will get saved.
// String file_path = context.getDir(folder,Activity.MODE_PRIVATE).getAbsolutePath();
return unzip(is,save_file_path);
for redirects
link
after u get response, again u ve to look for header fields

Unable to download file from FTP server using URLConnection having spaces in path

I'm Unable to download file from FTP server using URLConnection having spaces in pat
String s = "ftp://username:password#ftpclient:21/AAB BBC/hhhh 0001.jpg";
URL u = new URL(s);
URLConnection uc = u.openConnection();
BufferedOutputStream bos = new BufferedOutputStream(uc.getOutputStream());
Dont want FTP client solution.
Using URLencoder getting 550 error file not found.
Thanks,
Gaurav
Are you using Apache commons Library ? If so , use this code
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = FTP_object.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
You shouldn't have spaces in your URL itself per RFC1738 section 2.2 Run it through the URL Encode method to encode it:
String s = "ftp://username:password#ftpclient:21/AAB BBC/hhhh 0001.jpg";
String encodedUrl = URLEncoder.encode(s,"UTF-8");
I realize you said you were already doing the encoding, but that returned a 550 error. I didn't see the encoding so am just mentioning it should be needed.
I would really try this from a browser and see if you can get to it. I would also dump out the URL it is using and try that from a browser (or wget, curl, whatever you have handy). The 550 is listed as being a "permission" problem, not file not found, so I'm a little surprised at that, but that may be the short code and come up as an error to prevent people from poking around testing user/password combinations. Hard to say.
The other question I have for you is that you mention you don't want a client solution, but you seem to be writing a client not a server. You're going to port 21, which is the default FTP port for a server.
I would try various combinations of the encoding and see if maybe you're not encoding everything...you should encode the url path. Does the password have any funky characters in it?
Testing from the browser directly will give you a lot of insight.

How to use Android's CacheManager?

I'm currently developing an Android application that fetches images using http requests. It would be quite swell if I could cache those images in order to improve to performance and bandwidth use.
I came across the CacheManager class in the Android reference, but I don't really know how to use it, or what it really does.
I already scoped through this example, but I need some help understanding it:
/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java
Also, the reference states:
"Network requests are provided to this component and if they can not be resolved by the cache, the HTTP headers are attached, as appropriate, to the request for revalidation of content."
I'm not sure what this means or how it would work for me, since CacheManager's getCacheFile accepts only a String URL and a Map containing the headers. Not sure what the attachment mentioned means.
An explanation or a simple code example would really do my day. Thanks!
Update
Here's what I have right now. I am clearly doing it wrong, just don't know where.
public static Bitmap getRemoteImage(String imageUrl) {
URL aURL = null;
URLConnection conn = null;
Bitmap bmp = null;
CacheResult cache_result = CacheManager.getCacheFile(imageUrl, new HashMap());
if (cache_result == null) {
try {
aURL = new URL(imageUrl);
conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
cache_result = new CacheManager.CacheResult();
copyStream(is, cache_result.getOutputStream());
CacheManager.saveCacheFile(imageUrl, cache_result);
} catch (Exception e) {
return null;
}
}
bmp = BitmapFactory.decodeStream(cache_result.getInputStream());
return bmp;
}
I don't think the CacheManger can be used outside of a WebView as noted in this bug report
http://code.google.com/p/android/issues/detail?id=7222
I came across this issue awhile ago as well. The cache manager is only for the webview and not really useful outside of that. For my application I needed to cache xml responses and images so I ended up writing my own cache manager to accomplish that. Nothing too terrible but certainly not as easy as using a would-be built-in one.
If you have any questions about the specifics, add a comment to my post, I check back frequently.

Categories

Resources