日期:2014-05-16 浏览次数:20324 次
package com.cat.util; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.HttpURLConnection; import java.net.URL; public class TestHttpContion { private static String u; @SuppressWarnings("finally") public static String sendHttpProperty(String address) { StringBuffer returnStr = new StringBuffer(); u = address; URL url = null; HttpURLConnection httpurlconnection = null; try { url = new URL(u); httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; httpurlconnection.setDoInput(true); // Post 请求不能使用缓存 httpurlconnection.setInstanceFollowRedirects(true); httpurlconnection.setUseCaches(false); httpurlconnection.setRequestProperty("connection", "keep-alive"); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpurlconnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设定请求的方法为"POST",默认是GET httpurlconnection.setRequestMethod("POST"); // 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, httpurlconnection.setInstanceFollowRedirects(false); httpurlconnection.setConnectTimeout(2000); httpurlconnection.setReadTimeout(1000); httpurlconnection.setRequestProperty("Charsert", "UTF-8"); httpurlconnection.connect(); DataOutputStream out = new DataOutputStream( httpurlconnection.getOutputStream()); out.writeBytes(""); out.flush(); out.close(); DataInputStream reader = new DataInputStream( httpurlconnection.getInputStream()); byte[] buffer = new byte[4096]; int count = 0; while ((count = reader.read(buffer)) > 0) { String result = new String(buffer, 0, count); returnStr.append(result); } reader.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (httpurlconnection != null) { httpurlconnection.disconnect(); } return returnStr.toString(); } } }
?
这是一个用HttpURLConnection获取数据 并返回字符所获得字符串