开发者

Read XML from URL as a string

开发者 https://www.devze.com 2023-03-20 02:43 出处:网络
I 开发者_如何学Gohave a file as https://localhost/myeg.xml I want to read the file as string in Java.

I 开发者_如何学Gohave a file as https://localhost/myeg.xml I want to read the file as string in Java. Can somebody help me if there is a separate library or any way else.


You can try:

URL url = new URL(myfile);
InputStream is = url.openStream();
byte[] buf = new byte[1024];
int read = -1;
StringBuilder bld = new StringBuilder();
while ((read = is.read(buf, 0, buf.length) != -1) {
  bld.append(new String(buf, 0, read, "utf-8"));
}

String s = bld.toString();
  • This assumes utf-8, if the originating host does specify encoding, I would use .openConnection() and figure out the "content type" (and encoding) before reading the stream.
  • For performance you may want to wrap the InputStream in a BufferedInputStream.
  • You probably want a try-finally to close the InputStream


common-io:

URL url = new URL("https://etc..");
InputStream input = url.openStream();
String str = IOUtils.toString(input, "utf-8"); //encoding is important
input.close(); // this is simplified - resource handling includes try//finally

Or see examples in the official tutorial.


You could use Commons HTTP Client. See this example!

0

精彩评论

暂无评论...
验证码 换一张
取 消