ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • android.os.NetworkOnMainThreadException
    ANDROID 2017. 1. 31. 16:45
    반응형



    안녕하세요.


    android.os.NetworkOnMainThreadException


    메인스레드에서 네트워크 통신을 할려고 하셧군요~


    안드로이드에서 이건 절대 허용안한답니다.


    간단하게 코드로 보여드리겠습니다.



    수정전  - android.os.NetworkOnMainThreadException 오류발생


    String rtnVal = Request_Server_Login_Check(url, sel_member_id,sel_member_pw);


    수정후



    // Thread로 웹서버에 접속
    new Thread() {
    public void run() {
    try {
    String rtnVal = Request_Server_Login_Check(url, sel_member_id,sel_member_pw);
    DLog.d("bsj-mgr", rtnVal);
    } catch (IOException e) {
    e.printStackTrace();
    showDialogCommonAlert(R.string.xml_login_you_can_not_start_the_program_Connet_error_http);
    }
    }
    }.start();



    private String Request_Server_Login_Check(String urlStr,
    String sel_member_id, String sel_member_pw) throws IOException {
    StringBuilder output = new StringBuilder();
    System.out.println(urlStr);
    System.out.println(sel_member_id);


    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    Uri.Builder builder = new Uri.Builder()
    .appendQueryParameter("sel_member_id", sel_member_id)
    .appendQueryParameter("sel_member_pw", sel_member_pw);

    String query = builder.build().getEncodedQuery();

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(query);
    writer.flush();
    writer.close();
    os.close();

    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");
    }
    System.out.println("output==>" + output);

    reader.close();
    conn.disconnect();
    }
    return output.toString();
    }




    끝입니다!


    붉은색 글씨부분만 사용하시면 됩니다 ^^











    반응형

    댓글

Designed by Tistory.