由于URLConnection没有找到关闭对象的方法,所以选择了HttpURLConnection 类
一、get方式发送请求的代码
public String sendGet(String url) {
String message1 = "";
BufferedReader in = null;
URLConnection connection = null;
try {
URL realUrl = new URL(url);
connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setConnectTimeout(200);
connection.connect();
Map<String, List<String>> map = connection.getHeaderFields();
String str1;
for (Iterator localIterator = map.keySet().iterator(); localIterator
.hasNext(); str1 = (String) localIterator.next()) {
}
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
message1 = message1 + line;
}
if (in != null) {
in.close();
}
} catch (Exception e) {
message1 = "false123";
logger.error(e.toString());
}
return message1;
}
二、post方式发送请求的代码
HttpURLConnection connection = null;
OutputStream outStream = null;
ByteArrayOutputStream bos = null;
InputStream is_cg = null;
ByteArrayOutputStream bos_cg = null;
URL url = null;
try {
//发送post请求
url = new URL(url1);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", contentType);
outStream = connection.getOutputStream();
bos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int numread = 0;
while ((numread = is.read(buf)) != -1) {
bos.write(buf, 0, numread);
}
byte[] result = bos.toByteArray();
outStream.write(result);
//200时成功,可读取流操作
if (connection.getResponseCode() == 200) {
is_cg = connection.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; int len = -1; while ((len =
is_cg.read(buffer)) != -1) { outSteam.write(buffer, 0, len);
}
message = outSteam.toByteArray().toString();
System.out.println("请求广告主成功");
}