由于URLConnection没有找到关闭对象的方法,所以选择了HttpURLConnection 类
一、get方式发送请求的代码
HttpURLConnection connection = null;
try {
String url = "http://127.0.0.1:8080/dmapi/getAdlist";
URL realUrl;
realUrl = new URL(url);
connection = (HttpURLConnection)realUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
InputStream is = connection.getInputStream();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
}
二、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("请求广告主成功");
}
原文:http://www.cnblogs.com/qinpengyue/p/4892443.html