이 블로그 검색

2011년 3월 20일 일요일

HttpPut으로 서버에 Data 보내기

 거의 완벽한 예제가 있어서 퍼온다..
깔끔하게 정리가 잘되어 있음.. 감사.
http://roter.pe.kr/121

  1. public class PutJSONtoServer {   
  2.        
  3.     public PutJSONtoServer() {   
  4.   
  5.         String strURL = "/*WRITE DOWN SERVER ADDRESS*/"//이곳에 Server URL을 적자   
  6.                    
  7.         byte[] postBodyByte; //Entity로 보낼 려면 우선은 byte로 바꿔야 함   
  8.         String postBody=""//Entity로 보낼 값   
  9.            
  10.         postBody = "THIS IS THE ENTITY DATA";   
  11.         postBodyByte=postBody.getBytes(); //Entity를 Byte로 바꿔준다.   
  12.            
  13.         HttpEntity httpBody = new ByteArrayEntity(postBodyByte); //Byte로 바뀐 Entity를 HttpEntity로 바꿔준다.   
  14.         HttpResponse response = null;   
  15.         HttpParams params = new BasicHttpParams();    
  16.         HttpClient client = new DefaultHttpClient(); //HttpClient 선언   
  17.         HttpPut httpPut = new HttpPut(strURL); //만약 put이 아니고 post로 할거면 걍 HttpPost로 바꿔주면 된다.   
  18.         httpPut.setHeader("Content-type","application/json"); //이건 json쓸거라서 이렇게 했다.. 쓸 사람 맘대로 바꾸면 된다.   
  19.         httpPut.setEntity(httpBody); //이곳에 httpBody를 넣는다. httpBody는 엔티티이다~   
  20.         httpPut.setParams(params);   
  21.         try {   
  22.             response=client.execute(httpPut); //서버로 전송한다.   
  23.             Log.i("PUTJSONtoServer","SendJSONData");   
  24.         } catch (ClientProtocolException e) {   
  25.             e.printStackTrace();   
  26.         } catch (IOException e) {   
  27.             e.printStackTrace();   
  28.         }   
  29.         Log.i("PUTJSONtoServer","GET TATUS LINE: " + response.getStatusLine());    
  30.     }   

댓글 없음:

댓글 쓰기