Android > HttpClient - HttpPost() ¸¦ ÀÌ¿ëÇÑ ·Î±×ÀÎ ±¸Çö (Cookie,¼¼¼Ç À¯Áö Æ÷ÇÔ)
µî·ÏÀÏ : 2017-07-06 17:39
Á¶È¸¼ö : 145,635
¿À´ÃÀº HttpPost() ¸Þ¼µå¸¦ ÀÌ¿ëÇÑ ·Î±×ÀÎ ÈÄ ¼¼¼Ç À¯Áö ¹æ¹ýÀ» ¾Ë¾Æº¸µµ·Ï ÇÏ°Ú½À´Ï´Ù.
AndroidManifest.xml ¿¡¼ permission À» ¾Æ·¡Ã³·³ Ãß°¡ÇØ Áà¾ß °ÚÁö¿ä?
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
À§ÀÇ À̹ÌÁö ó·³ ·Î±×ÀÎ µðÀÚÀÎÀ» Çϱâ À§ÇØ main.xml ÆÄÀÏÀ» µðÀÚÀÎÇØ Áà¾ß ÇÕ´Ï´Ù.
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text_msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/login_msg" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="@string/login_id"
android:layout_width="100dip"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/edit_id"
android:inputType="text"
android:layout_width="200dip"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="@string/login_pw"
android:layout_width="100dip"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/edit_pw"
android:inputType="textPassword"
android:layout_width="200dip"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
>
<Button
android:id="@+id/btn_login"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:text="@string/login_btn"
/>
<Button
android:id="@+id/btn_web"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:text="@string/web_btn"
/>
</LinearLayout>
</LinearLayout>
À§¿¡¼ »ç¿ëÇÒ string º¯¼öµµ ¼±¾ðµÇ¾î¾ß °ÚÁÒ.
values/string.xml
<string name="app_name">LoginTest</string>
<string name="login_msg">·Î±×ÀÎÀ» ÇØÁÖ¼¼¿ä</string>
<string name="login_id">¾ÆÀ̵ð : </string>
<string name="login_pw">ºñ¹Ð¹øÈ£ : </string>
<string name="login_btn">·Î±×ÀÎ</string>
<string name="web_btn">À¥ºä1</string>
<string name="web_btn1">À¥ºä2</string>
À¥ºä ¹öÆ°À» ´·¶À»¶§ ¼¹ö ÆäÀÌÁö¿¡ Á¢¼ÓÇÒ webView¸¦ ¶ç¿ï ¾×ƼºñƼµµ Çϳª Ãß°¡ÇÕ´Ï´Ù.
layout/webview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="@+id/webview_test"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
></WebView>
</LinearLayout>
ÀÌÁ¦ java ¼Ò½ºÆÄÀÏÀ» º¸µµ·Ï ÇÏ°Ú½À´Ï´Ù.
LoginTestActivity.java
SessionControl.java
WebViewTest.java
3°³ÀÇ ÆÄÀÏÀÌ ÇÊ¿äÇÕ´Ï´Ù.
src/LoginTestActivity.java
public class LoginTestActivity extends Activity {
/** Called when the activity is first created. */
EditText et_id;
EditText et_pw;
TextView tv_msg;
private static String id = "";
private static String pw = "";
private static String msgString = null;
private static boolean isConnected = false;
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.enableDefaults();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_id = (EditText) findViewById(R.id.edit_id);
et_pw = (EditText) findViewById(R.id.edit_pw);
tv_msg = (TextView) findViewById(R.id.text_msg);
Button btn_web = (Button) findViewById(R.id.btn_web);
btn_web.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LoginTestActivity.this, WebViewTest.class);
startActivity(intent);
}
});
final Button btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id = et_id.getText().toString();
pw = et_pw.getText().toString();
sendPostRequest(id,pw);
}
});
}
private void sendPostRequest(String user_id, String user_pwd) {
class SendPostReqAsyncTask extends AsyncTask {
@Override
protected String doInBackground(String... params) {
String user_id = params[0];
String user_pwd = params[1];
Log.v("TAG","¹é±×¶ó¿îµå ÀÛ¾÷ user_id=" + user_id + " user_pwd=" + user_pwd);
//HttpClient httpClient = new DefaultHttpClient();
HttpClient httpclient = SessionControl.getHttpclient(); //º¯°æ
HttpPost httpPost = new HttpPost("http://ankyu.entersoft.kr/logintest.asp"); // ¿©·¯ºÐÀÇ ÁÖ¼Ò·Î º¯°æÇÒ °Í
BasicNameValuePair username = new BasicNameValuePair("user_id", user_id); // ¼¹öÀÇ ÇÁ·Î±×·¥¿¡ µû¶ó ´Þ¶óÁú¼ö ÀÖÀ½
BasicNameValuePair password = new BasicNameValuePair("user_pwd", user_pwd); // Æ÷½ºÆ®·Î º¸³»´Â º¯¼ö
List nameValuePairList = new ArrayList();
nameValuePairList.add(username);
nameValuePairList.add(password);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList,"UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// ·Î±×ÀÎ ¼º°ø½Ã ÄíÅ°¿¡ ÀúÀåÇÏÀÚ
SessionControl.cookies = SessionControl.httpclient.getCookieStore().getCookies();//Ãß°¡
//Àоî¿Â ÄíÅ°°ªÀ» Çѹø Ãâ·Â ÇÏ¿© º¸ÀÚ.
Cookie cookie;
if (!SessionControl.cookies.isEmpty())
{
for (int i = 0; i < SessionControl.cookies.size(); i++)
{
cookie = SessionControl.cookies.get(i);
Log.v("TAG","===>>>"+ cookie.toString() );
}
}
Log.v("TAG",stringBuilder.toString()); ///// ÀÌ°÷¿¡¼ ¼¹ö¿¡¼ º¸³»¿Â ¸Þ½ÃÁö¸¦ È®ÀÎÇØ º¼ ¼ö ÀÖ´Ù..
//¼º°ø/½ÇÆÐ ¿©ºÎ¿¡ µû¶ó ÀûÀýÈ÷ ´ëÀÀÇÏÀÚ.
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
Log.v("TAG","First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
Log.v("TAG","Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
Log.v("TAG","An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
//////////////////////////////////
// ÀÌ°÷¿¡¼ ·Î±×ÀÎÀ» À§ÇÑ À¥¹®¼¸¦ ºñµ¿±â ¹é±×¶ó¿îµå·Î ¿äûÇÑ´Ù.
SendPostReqAsyncTask sendTask = new SendPostReqAsyncTask();
sendTask.execute(user_id, user_pwd); // ºñµ¿±â ¹æ½Ä ¹é±×¶ó¿îµå·Î ¹Þ¾Æ ¿À±â.....
///////////////////////////////////
}
}
src/SessionControl.java
public class SessionControl {
static public DefaultHttpClient httpclient = null;
static public List cookies;
public static HttpClient getHttpclient() {
if( httpclient == null){
SessionControl.setHttpclient(new DefaultHttpClient());
}
return httpclient;
}
public static void setHttpclient(DefaultHttpClient httpclient) {
SessionControl.httpclient = httpclient;
}
}
src/WebViewTest.java
public class WebViewTest extends Activity {
String myUrlAddress ="http://ankyu.entersoft.kr/login_test1.asp";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView wv = (WebView) findViewById(R.id.webview_test);
///////////////// Ãß°¡µÈ ºÎºÐ /////////////
Cookie sessionCookie =null;
try {
if(!SessionControl.cookies.isEmpty())
{
sessionCookie=SessionControl.cookies.get(0);
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null)
{
cookieManager.removeSessionCookie();
String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
cookieManager.setCookie(myUrlAddress, cookieString);
CookieSyncManager.getInstance().sync();
}
}
}catch(Exception e){
e.printStackTrace();
}finally
{
}
/////////////////
wv.loadUrl(myUrlAddress);
wv.setWebChromeClient(new WebChromeClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.setInitialScale(1);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wv.setScrollbarFadingEnabled(false);
wv.setWebViewClient(new InfoWebViewClient());
}
public void onResume() {
super.onResume();
CookieSyncManager.getInstance().startSync();
}
public void onPause() {
super.onPause();
if (CookieSyncManager.getInstance() != null) {
CookieSyncManager.getInstance().stopSync();
}
}
private class InfoWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
//return false;
//}
view.loadUrl(url);
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//startActivity(intent);
return true;
}
//WebView°¡ ·ÎµùÀÌ ³¡³ª¸é ½ÃÀÛ
public void onPageFinished(WebView view, String url){
CookieSyncManager.getInstance().sync();
}
}
}
¼¹öÂÊ ÇÁ·Î±×·¥Àº ·Î±×ÀÎÆäÀÌÁö, ¼¼¼ÇÀ» È®ÀÎÇÒ ¼ö ÀÖ´Â ÆäÀÌÁö¸¦ ¸¸µé¾î¼ Å×½ºÆ® ÇØ º¸½Ã±â ¹Ù¶ø´Ï´Ù.
ÇÁ·ÎÁ§Æ® Àüü¼Ò½º¸¦ ÷ºÎÇÕ´Ï´Ù.
LoginTest.zip