HttpURLConnectionの使い方
1742 ワード
1.HttpURLConnectionサービスから情報を取得する
public void getInfo() throws IOException{
String respContent = "" ;
int code = 200;
String geoUrl = "http://www.hao123.com/?tn=98012088_1_hao_pg";
URL url = new URL(geoUrl);
// URLConnection , URL 。
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// ( )
httpURLConnection.setConnectTimeout(5*1000);
//
httpURLConnection.setDefaultUseCaches(false);
//URL , false
httpURLConnection.setDoOutput(false);
//URL , TRUE
httpURLConnection.setDoInput(true);
//
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// URL
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200){
//
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bytes = new byte[8024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int count = 0;
while((count = inputStream.read(bytes))!= -1){
bos.write(bytes, 0, count);
}
byte[] strByte = bos.toByteArray();
respContent = new String(strByte,0,strByte.length,"utf-8");
//
bos.close();
inputStream.close();
httpURLConnection.disconnect();
}
else{
code = httpURLConnection.getResponseCode();
}
System.out.println(code+" :"+respContent);
}