Java tutorial
//package com.java2s; /* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLConnection; public class Main { private static String consume(URLConnection connection) throws IOException { String encoding = getEncoding(connection); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = connection.getInputStream(); try { in = connection.getInputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } } finally { try { in.close(); } catch (IOException ioe) { // continue } } try { return new String(out.toByteArray(), encoding); } catch (UnsupportedEncodingException uee) { try { return new String(out.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException uee2) { // can't happen throw new IllegalStateException(uee2); } } } private static String getEncoding(URLConnection connection) { String contentTypeHeader = connection.getHeaderField("Content-Type"); if (contentTypeHeader != null) { int charsetStart = contentTypeHeader.indexOf("charset="); if (charsetStart >= 0) { return contentTypeHeader.substring(charsetStart + "charset=".length()); } } return "UTF-8"; } }