Java Code Examples for java.net.HttpURLConnection.getContentEncoding()

The following are Jave code examples for showing how to use getContentEncoding() of the java.net.HttpURLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: azeroth   File: HttpUtils.java   Source Code and License Vote up 7 votes
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    InputStream es = conn.getErrorStream();
    if (es == null) {
        String contentEncoding = conn.getContentEncoding();
        if (CONTENT_ENCODING_GZIP.equalsIgnoreCase(contentEncoding)) {
            return getStreamAsString(new GZIPInputStream(conn.getInputStream()), charset);
        } else {
            return getStreamAsString(conn.getInputStream(), charset);
        }
    } else {
        String msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else {
            throw new IOException(msg);
        }
    }
}
 
Example 2
Project: belling-spring-rabbitmq   File: HttpRequester.java   Source Code and License Vote up 6 votes
/**
 * 得到响应对象
 * 
 * @param urlConnection
 * @return 响应对象
 * @throws IOException
 */
private HttpRespons makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
	HttpRespons httpResponser = new HttpRespons();
	try {
		InputStream in = urlConnection.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,
				Charset.forName(this.defaultContentEncoding)));
		httpResponser.contentCollection = new Vector<String>();
		StringBuffer temp = new StringBuffer();
		String line = bufferedReader.readLine();
		while (line != null) {
			httpResponser.contentCollection.add(line);
			temp.append(line).append("");
			line = bufferedReader.readLine();
		}
		bufferedReader.close();

		String ecod = urlConnection.getContentEncoding();
		if (ecod == null)
			ecod = this.defaultContentEncoding;

		httpResponser.urlString = urlString;

		httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
		httpResponser.file = urlConnection.getURL().getFile();
		httpResponser.host = urlConnection.getURL().getHost();
		httpResponser.path = urlConnection.getURL().getPath();
		httpResponser.port = urlConnection.getURL().getPort();
		httpResponser.protocol = urlConnection.getURL().getProtocol();
		httpResponser.query = urlConnection.getURL().getQuery();
		httpResponser.ref = urlConnection.getURL().getRef();
		httpResponser.userInfo = urlConnection.getURL().getUserInfo();

		httpResponser.content = temp.toString();
		httpResponser.contentEncoding = ecod;
		httpResponser.code = urlConnection.getResponseCode();
		httpResponser.message = urlConnection.getResponseMessage();
		httpResponser.contentType = urlConnection.getContentType();
		httpResponser.method = urlConnection.getRequestMethod();
		httpResponser.connectTimeout = urlConnection.getConnectTimeout();
		httpResponser.readTimeout = urlConnection.getReadTimeout();

		return httpResponser;
	} catch (IOException e) {
		throw e;
	} finally {
		if (urlConnection != null)
			urlConnection.disconnect();
	}
}
 
Example 3
Project: Equella   File: Verb.java   Source Code and License Vote up 6 votes
public Response call()
{
	try
	{
		HttpURLConnection con = (HttpURLConnection) URLUtils.newURL(url, url.getPath() + generateParamaters())
			.openConnection();
		con.setConnectTimeout(10000);
		con.setRequestProperty("User-Agent", "OAIHarvester/2.0");
		String enc = con.getContentEncoding();
		if( enc == null )
		{
			enc = "UTF-8";
		}
		return (Response) xstream.fromXML(new UnicodeReader(con.getInputStream(), enc));
	}
	catch( IOException e )
	{
		throw new RuntimeException(e);
	}
}
 
Example 4
Project: azeroth   File: HttpUtils.java   Source Code and License Vote up 6 votes
private static HttpResponseEntity getResponseAsResponseEntity(HttpURLConnection conn) throws IOException {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    String charset = getResponseCharset(conn.getContentType());
    InputStream es = conn.getErrorStream();

    responseEntity.setStatusCode(conn.getResponseCode());
    if (es == null) {
        String contentEncoding = conn.getContentEncoding();
        if (CONTENT_ENCODING_GZIP.equalsIgnoreCase(contentEncoding)) {
            responseEntity.setBody(getStreamAsString(new GZIPInputStream(conn.getInputStream()), charset));
        } else {
            responseEntity.setBody(getStreamAsString(conn.getInputStream(), charset));
        }
    } else {
        String msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {
            responseEntity.setBody(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else {
            responseEntity.setBody(msg);
        }
    }

    return responseEntity;
}
 
Example 5
Project: appinventor-extensions   File: YandexTranslate.java   Source Code and License Vote up 6 votes
/**
 * This method reads from a stream based on the passed connection
 * @param connection the connection to read from
 * @return the contents of the stream
 * @throws IOException if it cannot read from the http connection
 */
private static String getResponseContent(HttpURLConnection connection) throws IOException {
  // Use the content encoding to convert bytes to characters.
  String encoding = connection.getContentEncoding();
  if (encoding == null) {
    encoding = "UTF-8";
  }
  InputStreamReader reader = new InputStreamReader(connection.getInputStream(), encoding);
  try {
    int contentLength = connection.getContentLength();
    StringBuilder sb = (contentLength != -1)
        ? new StringBuilder(contentLength)
        : new StringBuilder();
    char[] buf = new char[1024];
    int read;
    while ((read = reader.read(buf)) != -1) {
      sb.append(buf, 0, read);
    }
    return sb.toString();
  } finally {
    reader.close();
  }
}
 
Example 6
Project: appinventor-extensions   File: Web.java   Source Code and License Vote up 6 votes
private static String getResponseContent(HttpURLConnection connection) throws IOException {
  // Use the content encoding to convert bytes to characters.
  String encoding = connection.getContentEncoding();
  if (encoding == null) {
    encoding = "UTF-8";
  }
  InputStreamReader reader = new InputStreamReader(getConnectionStream(connection), encoding);
  try {
    int contentLength = connection.getContentLength();
    StringBuilder sb = (contentLength != -1)
        ? new StringBuilder(contentLength)
        : new StringBuilder();
    char[] buf = new char[1024];
    int read;
    while ((read = reader.read(buf)) != -1) {
      sb.append(buf, 0, read);
    }
    return sb.toString();
  } finally {
    reader.close();
  }
}
 
Example 7
Project: Shared-Route   File: CommonHttp.java   Source Code and License Vote up 4 votes
public static String postGetJson(String url, String content) {
        try {
            URL mUrl = new URL(url);
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            //设置链接超时时间
            mHttpURLConnection.setConnectTimeout(15000);
            //设置读取超时时间
            mHttpURLConnection.setReadTimeout(15000);
            //设置请求参数
            mHttpURLConnection.setRequestMethod("POST");
            //添加Header
            mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            //接收输入流
            mHttpURLConnection.setDoInput(true);
            //传递参数时需要开启
            mHttpURLConnection.setDoOutput(true);
            //Post方式不能缓存,需手动设置为false
            mHttpURLConnection.setUseCaches(false);

            mHttpURLConnection.connect();

            DataOutputStream dos = new DataOutputStream(mHttpURLConnection.getOutputStream());

            String postContent = content;

            dos.write(postContent.getBytes());
            dos.flush();
            // 执行完dos.close()后,POST请求结束
            dos.close();
            // 获取代码返回值
            int respondCode = mHttpURLConnection.getResponseCode();
            Log.d("respondCode","respondCode="+respondCode );
            // 获取返回内容类型
            String type = mHttpURLConnection.getContentType();
            Log.d("type", "type="+type);
            // 获取返回内容的字符编码
            String encoding = mHttpURLConnection.getContentEncoding();
            Log.d("encoding", "encoding="+encoding);
            // 获取返回内容长度,单位字节
            int length = mHttpURLConnection.getContentLength();
            Log.d("length", "length=" + length);
//            // 获取头信息的Key
//            String key = mHttpURLConnection.getHeaderField(idx);
//            Log.d("key", "key="+key);
            // 获取完整的头信息Map
            Map<String, List<String>> map = mHttpURLConnection.getHeaderFields();
            if (respondCode == 200) {
                // 获取响应的输入流对象
                InputStream is = mHttpURLConnection.getInputStream();
                // 创建字节输出流对象
                ByteArrayOutputStream message = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = is.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    message.write(buffer, 0, len);
                }
                // 释放资源
                is.close();
                message.close();
                // 返回字符串
                String msg = new String(message.toByteArray());
                Log.d("Common", msg);
                return msg;
            }
            return "fail";
        }catch(Exception e){
            return "error";
        }
    }