안드로이드 개발 질문/답변
(글 수 45,052)
HttpClient 를 이용하여 html을 긁어오고 그정보를 해석해서 정보를 화면에 뿌리는 걸 하려고합니다.
httpclient = new DefaultHttpClient();
httpget = new HttpGet(URL);
new Thread ( new Runnable(){
public void run() {
try {
response = httpclient.execute(httpget);
LOAD_PAGE_FLAG = true;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
while(!LOAD_PAGE_FLAG);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream instream = entity.getContent();
byte[] tmp = new byte[200000];
instream.read(tmp);
String contents = new String(tmp);
Log.i("content",contents);
}
html 소스를 긁어오는것 까지는 성공했습니다.
하지만 목표한 사이트의 html소스의 길이가 길다면(웹브라우져에서 소스보기로 보면 약 170kb 정도 됩니다.)
결과값을 Log를 이용해서 확인해보면 다가져오지 못하고 중간에 짤리게 됩니다.
이리저리 뒤지다가 buffer란걸 이용해보려고
HttpParams params = new BasicHttpParams();
int buff_size = 200000;
params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, buff_size);
httpclient = new DefaultHttpClient(params);
//httpclient = new DefaultHttpClient();
httpget = new HttpGet(URL);
new Thread ( new Runnable(){
public void run() {
try {
response = httpclient.execute(httpget);
LOAD_PAGE_FLAG = true;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
while(!LOAD_PAGE_FLAG);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream instream = entity.getContent();
byte[] tmp = new byte[200000];
instream.read(tmp);
String contents = new String(tmp);
Log.i("content",contents);
}
이런식으로 버퍼옵션을 주었는데도 여전히 다 가져오지못하고 아까와 같은 정도만 가져오게 됐습니다이문제를 어떻게 해결하면 좋을까요?
2010.04.25 17:53:41
instream.read() 호출 한 번에 모든 데이터를 읽어오는게 불가능할 수도 있습니다.
특히 네트워크를 통해서 데이터를 읽어오는 경우는 더욱 그렇지요.
instream.read() 의 리턴값을 확인해보세요.(읽은 바이트 수를 리턴합니다.)
모든 데이터를 읽어올 때까지 instream.read()를 반복호출하는 식으로 바꾸면 될 것 같습니다.
그런데 이 경우는 텍스트 데이터를 읽어오는 것이니 EntityUtils.toString() 메소드를 쓰면 간단하게 될 것 같네요.
2010.04.25 19:49:23
전 아래처럼 했습니다. 참고하세요.
Reader reader = new InputStreamReader(instream, HTTP.DEFAULT_CONTENT_CHARSET);
StringBuilder buffer = new StringBuilder();
try
{
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1)
buffer.append(tmp, 0, l);
}
finally
{
reader.close();
}
return buffer.toString();
Reader reader = new InputStreamReader(instream, HTTP.DEFAULT_CONTENT_CHARSET);
StringBuilder buffer = new StringBuilder();
try
{
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1)
buffer.append(tmp, 0, l);
}
finally
{
reader.close();
}
return buffer.toString();




BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while(null != (line = reader.readLine()))
{
sb.append(line);
sb.append('\n');
}
String result = sb.toString();