HttpURLConnection用法
URL请求的类别:
分为二类,GET与POST请求。二者的区别在于:a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
HttpUrlConnection用法
1.get请求
/** 网络的url地址 */String ticket_url="http://localhost:8080/web/dorm/studentfunction.do";/** http连接 */HttpURLConnection httpConn = null;
StringBuffer result= new StringBuffer();
try{
url = new URL(ticket_url);
BufferedReader in = new BufferedReader( newInputStreamReader(url.openStream(),"UTF-8") );String str = null;
while((str = in.readLine()) != null) {
result.append( str );
}
} catch (Exception ex) {
} finally{
try{
if(in!=null) {
in.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
String resultReturn = result.toString(); //返回结果字符串
2.post请求
// 表单参数与get形式一样
StringBuffer params = new StringBuffer();
params.append("param01").append("=").append(URLEncoder.encode("value01", "UTF-8"))
.append("&").append("param02").append("=").append(URLEncoder.encode("value02","UTF-8"));
/** 网络的url地址 */String ticket_url="http://localhost:8080/web/dorm/studentfunction.do";try {/** http连接 */HttpURLConnection httpConn = null;
url = new URL(ticket_url);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}// conn.setConnectTimeout(10000);//连接超时 单位毫秒 // conn.setReadTimeout(2000);//读取超时 单位毫秒 conn.setDoOutput(true);// 是否输入参数 byte[] bypes = params.toString().getBytes(); StringBuffer result= new StringBuffer(); BufferedReader in = null; try { conn.getOutputStream().write(bypes); InputStream inStream=conn.getInputStream(); in = new BufferedReader( new InputStreamReader(inStream,"UTF-8") ); String str = null; while((str = in.readLine()) != null) { result.append( str ); } //System.out.println(new String(readInputStream(inStream), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally{ try{ if(in!=null) { in.close(); } }catch(IOException e) { e.printStackTrace(); } } String resultReturn =result.toString(); //返回结果字符串