IT_Programming/Android_Java

HttpClient HTTP POST로 String 받는 두 가지 방법

JJun ™ 2011. 11. 27. 07:03

HttpEntity를 받아와서 바로 EntityUtils를 사용하여 String으로 바로 뽑아내는 것은

아래 코드로 가능하지만

 

   DefaultHttpClient httpClient = new DefaultHttpClient();

  HttpPost httpPost = new HttpPost("http://hako.04p.kr/");

  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

  nameValuePairs.add(new BasicNameValuePair("parameter1", "11"));

  nameValuePairs.add(new BasicNameValuePair("parameter2", "22"));

  httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

 

  HttpResponse httpResponse = httpClient.execute(httpPost);

  HttpEntity httpEntity = httpResponse.getEntity();

  String resultString = EntityUtils.toString(httpEntity);

 

 


InputStream으로 받아서 String으로 바꿔야 할 경우는 아래 코드를 사용한다.

 

  DefaultHttpClient httpClient = new DefaultHttpClient();

  HttpPost httpPost = new HttpPost("http://hako.04p.kr/");

  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

  nameValuePairs.add(new BasicNameValuePair("parameter1", "11"));

  nameValuePairs.add(new BasicNameValuePair("parameter2", "22"));

  httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  HttpResponse httpResponse = httpClient.execute(httpPost);

  HttpEntity httpEntity = httpResponse.getEntity();

  InputStream inputStream = httpEntity.getContent();

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 

  while (true) {

           byte[] temp = new byte[8 * 1024];

           int readLength = inputStream.read(temp);

           if (readLength < 0)

                   break;

 

           byteArrayOutputStream.write(temp, 0, readLength);

  }

 

  inputStream.close();

  byte[] buffer = new byte[1024 * 1024];

  buffer = byteArrayOutputStream.toByteArray();

  String resultString = new String(buffer);