Java Load image from URLConnection - java

I have a URLConnection, that access a web page.
URL url = new URL("https://domain");
con = url.openConnection();
con.setDoOutput(true);
Then i sent some data to the server using con.setRequestProperty()
I get the response cookies fro ma specified field using
String headerValue = con.getHeaderField(6);
I also get the html and parse an image url from there. But here is a problem. I can get this image only by sending cache data back to the server ,when i acces my image.
So i open a new connection
URL url1 = new URL("https://domain/image);
URLConnection con1 = url1.openConnection();
I send the cookies back to the server con1.setRequestProperty("Cookie", headerValue);
And finally i try to acces the image using BufferedInputStream and then creating an iamge in a JLabel
BufferedInputStream in = new BufferedInputStream(con1.getInputStream());
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
byteArrayOut.write(c);
}
Image image = Toolkit.getDefaultToolkit().createImage(
byteArrayOut.toByteArray());
label.setIcon(new ImageIcon(image));
The problem is this seems to not work. Is it another way to get an file from a server through a URlConnection?
Error code
Server returned HTTP response code: 400 for URL: https://domain/image
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
Thanks in advance

Found the error. Case closed.
Used this code to split the cookies string.
String temp = headerValue.substring(0, (len1-17));

Related

Is there any way to get the SEDE query result from my Java program using Stack Exchange API?

I want to get a query result from Stack Exchange API using my Java program. For example, I want to pass this URL and get the data of the question with id 805107. I have tried but only got the resulted web page content. I did not get the query result, i.e. the question data, although the resulted page shows the question data.
url = new URL ("https://api.stackexchange.com/docs/questions-by-ids#order=desc&sort=activity&ids=805107&filter=default&site=stackoverflow&run=true");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
String encoding = new String (encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput (true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
As Stephen C said, you need to use the query URL, not the URL of the documentation. You can find the query URL in the "Try it" part of the documentation page. Try using
url = new URL ("https://api.stackexchange.com/2.2/questions/805107?order=desc&sort=activity&site=stackoverflow")
It will return the result you are looking for as JSON like it is displayed on the documentation page.

Need help on downloading a text file from a site using HttpsUrlConnection java class

I want to read the content of a text file which is located in the site
https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt
I want to read it using Java . I started it with using HttpsUrlConnection Class .
When we take the above URL in the browser , we will first redirect to a agreement page and if we click the agree button , we can see the text file . How we can do the same procedure using HttpsUrlConnection class ?
This is what I tried:
URL url = new URL("https://www.frbservices.org/EPaymentsDirectory/submitAgreement?agreementValue=Agree");
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setRequestMethod("POST");
https.connect();
url = new URL("https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt");
HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.connect();
String line = "";
BufferedReader in = new BufferedReader( new InputStreamReader(http.getInputStream()));
while( (line = in.readLine()) != null )
{System.out.println(line);
//process line
logger.debug(line);
processLine(line);
}
http.disconnect();
Any inputs will be highly appreciable
Looks like the POST request to accept the agreement results in a session cookie from the server which likely stores whether or not the agreement is accepted. You could try getting the JSESSIONID cookie from the "Set-Cookie" header and sending it in your "Cookie" header to simulate the behaviour of the browser.

Picasa getAlbum request not working Android

String album = "http://picasaweb.google.com/data/feed/api/user/"+email;
HttpURLConnection con = (HttpURLConnection) new URL(albumUrl).openConnection();
// request method, timeout and headers
con.setRequestMethod("GET") ;
con.setReadTimeout(15000);
con.setRequestProperty("Authorization", "GoogleLogin auth="+auth);
con.setRequestProperty("GData-Version", "2");
// set timeout and that we will process output
con.setReadTimeout(15000);
con.setDoOutput(true);
// connnect to url
con.connect();
// read output returned for url
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Problem : Everytime i call con.getInputStream() it gives me file not found exception.
But when i load the same url in the desktop browser then it is displaying correct data.
I am confused why on android it is throwing exception.
Thanks in advance.
Did you get this? Maybe you just missed the https
below example uses default for authenticated user and the experimental fields list.
url = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&access=public&fields="
+ URLEncoder
.encode("entry(title,id,gphoto:numphotosremaining,gphoto:numphotos,media:group/media:thumbnail)",
"UTF-8");
https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbums

Download a file from a page (cookies needed) using post request

I have tested the first step (the login page) and it works. I put all parameters (user, pass, etc) and I can print the result (page with my data). The problem is when I try to download a file from that web. I need the cookies from the first step. In the file that I download I have the message: "Expired session". This is my code:
URL login = new URL("...");
URL download_page = new URL("...");
URL document_link new URL("...");
//String for request
String data_post = "username=name&password=1234&other_data=...";
//Login page
HttpURLConnection conn = (HttpURLConnection)login.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_post);
wr.close();
conn.connect();
//Download page
HttpURLConnection connDownload = (HttpURLConnection)download_page.openConnection();
connDownload.connect();
//Link to the file
HttpURLConnection connFile = (HttpURLConnection)document_link.openConnection();
connFile.connect();
BufferedInputStream in = new BufferedInputStream(connFile.getInputStream());
File saveFile = new File("myfile.txt");
OutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
byte[] buf = new byte[256];
int n = 0;
while ((n=in.read(buf))>=0) {
out.write(buf, 0, n);
}
out.flush();
out.close();
Thanks in advance.
Have you tried to check the headers for a cookie on the first page before closing the connection? I'd try something like:
String cookies = conn.getHeaderField("Set-Cookie");
Then set the cookie subsequently in the following connections, before executing connect(), using:
connDownload.setRequestProperty("Cookie", cookies);
... See if that works ...

Problem in getting url.getContent()

I have a problem in my hand.
I have a URL, And when i initiate the connect to this url and execute url.getContent().
The response is of type sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
I tried to assign the output to HttpURLConnectionHttpInputStream h = url.getContent(). But i was unsuccessful.
I imported corresponding libraries to code, but still no luck.
If i inspect the url.getContent() in eclipse, it also shows the variable thei$0 in it.
All i need is a URL in this$0. But till now i am unable to retreive it.
In this$0 there is a variable names url and i am trying to fetch it.
I also have hard time understand this$0 and hoe to retrieve it.
After using the streams i get some non readable output
Regards
Dheeraj Joshi
You should use the openStream method of the url class.
Code snippet:
InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
If the output is not in a readable string format, then use:
InputStream in = url.openStream();
byte[] buffer = new byte[512];
int bytesRead = in.read(buffer);
I found the answer.
The problem statement: When i execute a URL the response had another URL in it and i needed to fetch it.
Solution:
java.net.URLConnection urlconn = url.openConnection();
java.net.HttpURLConnection conn = (java.net.HttpURLConnection)urlconn;
conn.connect();
conn.getContent();
URL newurl = conn.getURL();
System.out.println(newurl.toString());
The response can be get using getContent() and. The connection object will have a delegate with the new URL. The new URL can be fetched using getURL method.
Regards
Dheeraj Joshi

Categories

Resources