최근 HttpClient로 검색하면 거의 Apache Commons 프로젝트로서의 httpClient 만 사용하고 있어서
Apache Commons 에서 분리 되여 독립 프로젝트 HttpClient 4.3.2 버전으로 사용한 내용 올려 봅니다.
1. Client 생성
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpClient 를 사용하여 여러번 호출 가능.
로그인후 세션 공유 가능.
2. Client 종료
client.close();
3. 로그인
HttpPost post = new HttpPost("[로그인할 submit url 주소]");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("ID", id));
paramList.add(new BasicNameValuePair("PASSWORD", pw));
paramList.add(new BasicNameValuePair("OTHER", "기타"));
post.setEntity(new UrlEncodedFormEntity(postParams));
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String line = "";
while((line = rd.readLine()) != null) {
result.append(line);
}
}
finally {
response.close();
}
}catch(Exception e){
e.printStackTrace();
}
4. 로그인 후 데이터 요청
String httpurl = "데이터 요청할 url";
OutputStream ostream;
HttpGet get = new HttpGet(httpurl);
CloseableHttpResponse response;
try {
response = client.execute(get);
InputStream inputStream = (InputStream)response.getEntity().getContent();
/**
* InputStream을 바로 POI로 읽어서 처리
* (데이터가 Excel 파일 일 때)
*/
//Workbook wb = WorkbookFactory.create(inputStream);
//Sheet sheet = wb.getSheetAt(0);
/**
* InputStream을 파일로 생성하여 처리
*/
File file = new File("D:/tmp" + dealId + ".xlsx");
ostream = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
while(true) {
final int len = inputStream.read(buffer);
if(len <= 0) {
break;
}
ostream.write(buffer, 0, len);
}
ostream.close();
response.close();
}
catch(IOException e) {
e.printStackTrace();
}
catch(InvalidFormatException e) {
e.printStackTrace();
}
finally {}
댓글 없음:
댓글 쓰기