안규 공부방

Android > HttpURLConnection - 접속방법

등록일 : 2017-07-06 17:32 조회수 : 93,547

자바에서 HTTP 클라이언트를 만드는 가장 간단한 방법은 URL 객체를 만들고 이 객체의 openConnection() 메소드를 호출하여

HttpURLConnection 객체를 만드는 것입니다.



HttpURLConnection 객체를 이용해 웹에 접근후 결과 값에 따라서 프로그래밍 처리하는 기법을 나타냅니다.
 
	try {
		//휴대폰번호 받기
		String _PhoneNo = "";	//휴대폰번호
		TelephonyManager telephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
		_PhoneNo = telephony.getLine1Number();
	
		if(_PhoneNo==null)
		{
			_PhoneNo = "";
		}
	
		url = new URL("http://entersoft.kr/member/member_login_ok.asp?phoneno="+_PhoneNo);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
		StringBuffer buffer = new StringBuffer();
		
		int c;
		while((c=in.read()) != -1)
		{                
			buffer.append((char)c);            
		} 
	
		_Url_ReturnChk = buffer.toString();
	
		if(_Url_ReturnChk.equals("OK"))
		{
			Toast.makeText(getApplicationContext(),"로그인이 성공하였습니다.",500).show();
		                  		
			Member_Login.this.finish();
			Intent myIntent1 = new Intent(getApplicationContext(), Main_Menu.class);
			startActivity(myIntent1);
		}
		else
		{
			Toast.makeText(getApplicationContext(),"로그인이 실패하였습니다.",500).show();
		}
	} catch (MalformedURLException e)	{            
		e.printStackTrace();        
	} catch (IOException e) 
	{            
		e.printStackTrace();        
	}
	


아래 소스는 예외 상황까지 고려한 기본 샘플 예제 입니다.

리턴된 문자열을 받아 txtMsg 에 뿌려주는 예제 입니다.

 
	String urlStr = "http://m.naver.com";
	String  output = request(urlStr);	//request() 메소드 호출	
	txtMsg.setText(output);		//결과물 출력

	private String request(String urlStr) {
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			if(conn!=null) {
				conn.setConnectTimeout(10000);
				conn.setRequestMethod("GET");
				conn.setDoInput(true);
				conn.setDoOutput(true);

				int resCode = conn.getResponseCode();

				if(resCode == HttpURLConnection.HTTP_OK) {
					BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line = null;

					while(true) {
						line = reader.readLine();
						if(line==null) {
							break;
						}

						output.append(line + "\n");
					}

					reader.close();
					conn.disconnect();
				}
			}
		}catch(Exception ex) {
			Log.e("SampleHTTP","Exception in processing response.",ex);
		}

		return output.toString();
	}


 
※ 혹시 도움이 되셨다면 댓글에 한마디 남겨주세요!
작성자   비밀번호
자동글 방지     (자동글 방지 기능입니다.)
내용   댓글달기 
이메일 문의 : cak0280@nate.com  
Copyright 2000 By ENTERSOFT.KR All Rights Reserved.