2015년 9월 5일 토요일

http 요청하기

http 요청을 하고 데이터를 받아올 때에는 AsyncTask를 통해서 
UI 쓰레드와 별도의 쓰레드에서 진행이 되어야 합니다. 

AndroidManifest.xml에는 다음 2권한을 넣어줍니다.

      <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


MainActivity.java



public class MainActivity extends FragmentActivity {

 private FragmentManager fm;
 private LoadingDialog loadingDlg;
 private TextView tv;

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE); 
  setContentView(R.layout.activity_main);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);

  fm = ((FragmentActivity)this).getSupportFragmentManager();

  tv = (TextView)findViewById(R.id.textView1);
  
  loadingDlg = new LoadingDialog();
  loadingDlg.setMsg("loading...");
  loadingDlg.setCancelable(false);
  loadingDlg.setNoBtn(true);

  loadingDlg.show(fm, null);
  retrieveContent();
 }

 private void retrieveContent() {
  new AsyncTask<Void, Void, String>() {
   @Override
   protected String doInBackground(Void... params) {
    return getWebPage("http://url/read");
   }

   @Override
   protected void onPostExecute(String result) {
    tv.setText(result);
    loadingDlg.dismiss();
   }
  }.execute(null, null, null);
 }

 public String getWebPage(String webpage) {
  String result = "";
  HttpURLConnection urlConnection = null;

  try {
   URL url = new URL(webpage);
   urlConnection = (HttpURLConnection) url.openConnection();
   urlConnection.setRequestMethod("POST");
   urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
   urlConnection.setRequestProperty("charset", "UTF-8");
   urlConnection.setConnectTimeout(6000);
   urlConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
   urlConnection.setDoInput(true);
   urlConnection.setDoOutput(true);

   DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
   BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
   writer.close();
   wr.close();

   int responseCode = urlConnection.getResponseCode();
   if (responseCode == 200) {
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
     result = result + inputLine; 
    }
    in.close();
   }
  }
  catch (Exception e) {
   String msg =  e.toString();
  }
  finally { 
   urlConnection.disconnect(); 
  }

  return result;
 }
}

LoadingDialog.java


public class LoadingDialog extends DialogFragment {

 String msg;
 boolean noBtn = false;

 public void setMsg(String msg) { this.msg = msg; }
 public void setNoBtn(boolean no) { this.noBtn = no; }

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  LayoutInflater li = LayoutInflater.from(getActivity());
  View promptsView = li.inflate(R.layout.info_dialog, null);
  
  Button okBtn = (Button)promptsView.findViewById(R.id.button1);
  okBtn.setText("Ok");
  okBtn.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    dismiss();
   }
  });

  if (noBtn) { okBtn.setVisibility(View.INVISIBLE); }
  else {  okBtn.setVisibility(View.VISIBLE);  }
  
  TextView tv = (TextView)promptsView.findViewById(R.id.textView1);
  tv.setText(msg);

  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
  alertDialogBuilder.setView(promptsView);

  AlertDialog alertDialog = alertDialogBuilder.create();

  return alertDialog;
 }
}

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

</RelativeLayout>



info_dialog.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="Ok" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Info" />

</RelativeLayout>



댓글 없음:

댓글 쓰기