Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So I have this rather weird problem with my program. What I try to do is to check the Content-Length of a URL and then use this number in a non-static method with an if-else statement connecting other classes. But my problem with this is that while I was researching the internet to somehow solve this problem, there where these static-methods that I could use to get the contentLength and it wouldn't work with non-static. So I tried it but I never really got any results. What I basically tried to do is to call the class with the static-method via non-static-method in another class which, I guess, shouldn't be the problem (or should? I don't really know since I have never worked with static methods before). Then I used this code to determine the contentLength of a random webpage with changing date:
public static void main() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 1); // Adding 1 day
String output = sdf.format(c.getTime());
try {
String urlStr = "http://www.sasintern.de/show_pdf.php?fn=" + output + ".pdf";
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int contentLength = httpConn.getContentLength();
if (contentLength < 2000) {
new NotWorkingActivity();
System.out.println("unknown content length");
} else {
new download2Activity();
System.out.println("content length: " + contentLength + " bytes");
}
InputStream inStream = httpConn.getInputStream();
// now read data
// ...
// close connection
httpConn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Afterwards, when the size of the page was determined to be smaller than 2000 bytes, it should show a Toast in another class that the page is not available, but when it was bigger, then it should open up a new class, as you may see in the else-statement.
But it doesn't work and I think I just messed up with static methods. I'm just not that experienced with them. Sorry for any other mistakes that I might have made. If there is an different solution to my problem which, hopefully, is easier to understand and better to use, I would be very grateful.
Please, I need help on this problem and I hope you understand what I am up to.
Thanks in advance :)
Read the manual
http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getContentLength()
public int getContentLength()
Returns the value of the content-length header field.
Not all resources set the Content-Length header. So, you need to obtain input stream and read all the bytes until the end to count them.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
I tried to do "image = (PNMImage) ois.read(getBytes(fileName);" in order to fix the issue of converting string to byte but I got an error that said, cannot resolve getBytes in PNMimage
// TODO Implement this method
// return null;
PNMImage image = null;
try {
DataInputStream ois = new DataInputStream(new FileInputStream(fileName));
image = (PNMImage) ois.read(getBytes(fileName));
}catch(ClassNotFoundException e ) {
e.printStackTrace();
}
return image;
}```
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to get a copy of the content from the stream without consuming it. My plan is to use this original stream in the later of the code. Following is the sample code I tried to check this. My intention is to keep the original InputStream for future use after getting a copy
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamTest {
public static void main(String[] args) {
try {
InputStream inputstream = new FileInputStream("resource.txt"); // content of the file is 'test'
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(inputstream, baos);
byte[] bytes = baos.toByteArray();
System.out.println("copied stream : " + new String(bytes));
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
System.out.println("original stream : " + sb.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
but still, when I access the original stream, after coping it, I still see that the original stream is consumed. See below output
copied stream : test
original stream :
Can someone point out my mistake
Thanks
Sadly this is not possible by the nature of streams.
In order to copy the data from the stream, you need to first extract it. By extracting it, you consume the stream.
But do not worry, there should be a solution for your specific use case. Maybe open another stream (if you know the source of the stream gives the same data every time - as in a file - , you can use Supplier everywhere you would use the InputStream, so that a new stream is created whenever necessary), or you can check out this post for creating more streams with the same data: https://stackoverflow.com/a/5924132/3102234
Recently, as a bit of a personal curiosity project, I have been writing an incredibly simple bot to use on Poloniex (a cryptocurrency exchange). I have been able to get the public API to work properly, but when I started testing the trading API, things started to fall apart. When I run this (and the 30 something other variations in an attempt to get things to work) all I get is
{"error":"Invalid command."}. I am new to using basically every single one of the libraries I am using, so there's a huge margin for error that I can't narrow down.
Poloniex API documentation is here: https://poloniex.com/support/api/
public String returnBalances() {
try {
long nonce = System.nanoTime();
String params = "command=returnBalances&nonce=" + nonce;
URL u = new URL(URL_PRIVATE + "?" + params);
String sign = getSign(params);
if(sign == null) return null;
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.setRequestProperty("Key", API_Key);
huc.setRequestProperty("Sign", sign);
huc.setRequestProperty("nonce", String.valueOf(nonce));
return getDataFromHUC(huc);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String getSign(String c) {
try {
SecretKeySpec mac_key = new SecretKeySpec(API_secret.getBytes(), "HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(mac_key);
String sign = bytesToHex(mac.doFinal((c).getBytes()));
return sign;
}
catch (Exception e) {
return null;
}
}
private String getDataFromHUC(HttpURLConnection huc) {
try {
huc.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
String data = sb.toString();
return data;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
Furthermore, while I was googling stuff to find an answer, I found that not a single person uses the java.net libraries (which I am). Have I completely missed base on what I should be doing? I would prefer to use these libraries if possible so I can really learn what's going on behind the scenes as much as I am able.
Sorry if there's an obvious answer either here or somewhere else on this website. I've been at this for hours now with no progress so I'm bound to make mistakes.
P.S. I am aware that my run-time error handling is probably pretty low quality, but I haven't had any problems with it so improving it is kind of a low priority.
As described in the provided documentation, the whole TradingAPI requires POST requests.
So instead of huc.setRequestMethod("GET"); you'll need huc.setRequestMethod("POST");
You'll also probably need to enable in- and outputs after that:
huc.setDoInput(true);
huc.setDoOutput(true);
And don't forget to set your Content-Type and Content-Length:
huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty("Content-Length", params.length());
And instead of adding the parameters to the end of your URL, you need to write them to the output (right after setting the request properties):
DataOutputStream os = new DataOutputStream(huc.getOutputStream());
os.writeBytes(params);
os.flush();
It also seams like you don't need to send the nonce as a request property.
I hope this helps!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a code that is running on NodeJs. We would like to change the technology (to java).
The problem is we have some existing passwords, and I am not sure how to I copy the encryption logic to java.
So, one of the possible solutions is to run the encryption logic in javascript (e.g. command line, embbeded in the java, etc) and get the result back.
The question is - how do I do that?
The nodejs code goes like this:
crypto = require('crypto');
this.salt = this.makeSalt();
encryptPassword: function(password) {
var salt = new Buffer(this.salt, 'base64');
return crypto.pbkdf2Sync(password, salt, iterations, keylen).toString('base64');
crypto.randomBytes(..)
}
makeSalt: function() {
return crypto.randomBytes(numOfBytes).toString('base64');
},
UPDATE:
Following the suggestions here, I added the full code. If the right way of doing it is by transforming the javascript code to java code, can you please help me translated the above code?
You should not do this, if you want random bytes in Java do this. You should be able to replicate the encryption logic in Java.
byte[] b = new byte[20];
new Random().nextBytes(b);
Almost all of the Node.js crypto functions are generic, and should have their own Java counterparts or 3rd party libraries.
Update
If you must run your node code via java you can add this method
public static String runCommand(String command) {
String output = "";
try {
String line;
Process process = Runtime.getRuntime().exec( command );
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()) );
while ((line = reader.readLine()) != null) {
output += line;
}
reader.close();
} catch (Exception exception) {
// ...
}
return output;
}
and run it like this
String encryptedPassword = runCommand("node myEncryption.js --password=1234");
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am developing a java web application and I want to know how to take a certain field (table and/or output-text) value from a certain website. Assuming that this component has always the same ID does anyone know how can I retrieve this information?
I don't know if anyone has ever faced this issue but if anyone has any idea please share.
Thank you.
In general:
1.) Retrieve the pages markup by reading it through an HTTPConnection to the URL in your application
2.) Parse the Markup using a framework like jsoup and retrieve the value you need.
More specifically, here is some example code for jsoup:
HttpClient http = new DefaultHttpClient();
String htmlcode = "";
HttpGet request = new HttpGet("http://www.example.com");
HttpResponse response = null;
try {
response = http.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(response != null){
BufferedReader read = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while((line = read.readLine()) != null){
htmlcode += line;
}
}
// at this point we have the pages markup
Document doc = Jsoup.parse(htmlcode);
Elements lis = doc.getElementsByTag("li"); // get all entries in lists
for(Element el : lis){
String val = el.text().trim();
// do something for each list entry
}
You are talking about web scraping, check this library for php:
http://simplehtmldom.sourceforge.net/