android HttpClient 예제 get, post 방식


get방식

      HttpClient client = new DefaultHttpClient();
      String url = "http://localhost:8080";
      HttpGet get = new HttpGet(url);
      HttpResponse response = client.execute(get);
      HttpEntity resEntity = response.getEntity();
      if(resEntity != null){
       Log.w("reponse", EntityUtils.toString(resEntity));       
      }


위 소스에서 try~ catch를 적용하면

      HttpClient client = new DefaultHttpClient();
      String url = "http://localhost:8080";
      HttpGet get = new HttpGet(url);
      HttpResponse response = null;
		try {
			response = client.execute(get);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      HttpEntity resEntity = response.getEntity();
      String sRes = "";
      if(resEntity != null){
	       try {
		   sRes = EntityUtils.toString(resEntity);  
		   //sRes = URLDecoder.decode(sRes);
		   Log.w("SNSApp", "response: " + sRes);  
		   Toast.makeText(mContext, sRes, Toast.LENGTH_SHORT).show();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}       
      }	


     

post방식

      HttpClient client = new DefaultHttpClient();
      String postUrl = "http://222.jsp";
      HttpPost post = new HttpPost(postUrl);
      List params  = new ArrayList();
      params.add(new BasicNameVal!uePair("deliveryDate", "1111111111"));
      
      UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
      post.setEntity(ent);
      HttpResponse responsePost = client.execute(post);
      HttpEntity resEntity = responsePost.getEntity();
      if(resEntity != null){
       Log.w("Response", EntityUtils.toString(resEntity));
      }

 

출처 : http://cafe.naver.com/infinityjava/206


+ Recent posts