본문 바로가기
프로그래밍 놀이터/안드로이드, Java

[android/안드로이드] Restful Get sample code.

by 돼지왕 왕돼지 2012. 10. 4.
반응형



 

Restful Get 은 Post 와 똑같다. 다만, HttpPost 대신 HttpGet Class 를 사용하면 된다.

HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost( url );

// Parameters setting. 

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

nameValuePairs.add( new BasicNameValuePair( key1value1 ) );

nameValuePairs.add( new BasicNameValuePair( key2value2 ) );


try{

  httpPost.setEntity( new UrlEncodedFormEntity( nameValuePairs ) );

  HttpResponse httpResponse = httpClient.execute( httpPost );

  HttpEntity entity = httpResponse.getEntity();

  if ( entity != null ){

    InputStream ins = entity.getContent();

    String result = convertStreamToString( ins );

    try {

      ins.close();

    } catch (IOException e) {

       e.printStackTrace();

    }

    JSONObject json = new JSONObject( result );

    try{

      return json.getString( KEY_ID );

    }

    catch( Exception e ){

      e.printStackTrace();

    }

  }

}

catch( Exception e ){

  e.printStackTrace();

}

return null;



private static String convertStreamToString( InputStream ins ){

  BufferedReader reader = new BufferedReader( new InputStreamReader( ins ) );

  StringBuilder sb = new StringBuilder();

 

  String line = null;

  try {

    while ((line = reader.readLine()) != null) {

      sb.append(line + "\n");

    }

  } catch (IOException e) {

     e.printStackTrace();

  }

  return sb.toString();

} 

 
 
도움이 되셨다면 손가락 꾸욱~ ( 로그인 필요 x )



 
반응형

댓글