2014-10-25 3 views
-1

사용자를 만들고 서버에 사용자 이름과 암호를 POST하려고합니다. 아래의 코드는 일반 Java 파일에서 정상적으로 실행되지만안드로이드 네트워크 AsyncTask

android.os.NetworkOnMainThreadException 때문에 Android에서 실행할 때 다운됩니다.

검색을 수행하고 AsyncTask를 사용하도록 지시 받았지만 AsyncTask를 사용하는 방법, 매개 변수를 실행하고 전달하는 방법을 알지 못합니다. url과 account Info를 전달해야합니다. 둘 다 String입니다.

다음은 일반 자바 파일에서 실행되는 코드입니다.

public String sendPost(String accountInfo, String input_url) throws Exception { 

    // Establish Connection 
    URL url = new URL(input_url); 
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
    con.setRequestMethod("POST"); 
    con.setDoOutput(true); 

    // Post account info to server 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.writeBytes(accountInfo); 
    wr.flush(); 
    wr.close(); 

    // Check response code and message 
    int responseCode = con.getResponseCode(); 
    IntputStream is = con.getErrorStream(); 
    String contentAsString = CovertToString(is, 500); 
    JSONObject jObject = new JSONObject(contentAsString); 
    jObject.put("response", responseCode); 

    return jObject; 
} 

다음은 AsyncTask로 만들려고 시도한 것입니다.

class Test extends AsyncTask<String, Void, Void>{ 

    @Override 
    protected Void doInBackground(String... params) { 
     try { 
      // Establish Connection 
      URL url = new URL(input_url); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      con.setRequestMethod("POST"); 
      con.setDoOutput(true); 

      // Post account info to server 
      DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
      wr.writeBytes(accountInfo); 
      wr.flush(); 
      wr.close(); 

      // Check response code and message 
      int responseCode = con.getResponseCode(); 
      IntputStream is = con.getErrorStream(); 
      String contentAsString = CovertToString(is, 500); 
      JSONObject jObject = new JSONObject(contentAsString); 
      jObject.put("response", responseCode); 

     }catch (IOException e) { 
      e.printStackTrace(); 
     } 

    return null; 

    } 
} 

메서드를 호출하고 매개 변수를 전달하는 방법을 모르거나 메서드를 올바르게 구현했는지 확실하지 않습니다.

미리 감사드립니다. 감사합니다.

답변

3

.

class Test extends AsyncTask<String, Void, JSONObject>{ 

    @Override 
    protected JSONObject doInBackground(String... params) { 
     JSONObject jObject = null; 
     try { 
      String accountInfo = params[0]; 
      String input_url = params[1]; 
      // Establish Connection 
      URL url = new URL(input_url); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      con.setRequestMethod("POST"); 
      con.setDoOutput(true); 

      // Post account info to server 
      DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
      wr.writeBytes(accountInfo); 
      wr.flush(); 
      wr.close(); 

      // Check response code and message 
      int responseCode = con.getResponseCode(); 
      IntputStream is = con.getErrorStream(); 
      String contentAsString = CovertToString(is, 500); 
      jObject = new JSONObject(contentAsString); 
      jObject.put("response", responseCode); 

     }catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return jObject; 

    } 

    protected void onPostExecute(JSONObject data) { 
    // do further things with JSONObject as this runs on UI thread. 

    } 

} 

은 AsyncTask를에 대한 자세한 내용은 here를 참조하십시오 .. 작업을 호출 당신이 거기에서 UI 작업을 호출 할 수 있도록

new Test().execute(accountInfo, input_url); 

onPostExecute가 UI 스레드에서 호출되는 호출합니다.

1

는 등 데이터를 게시 해보십시오 :이 같은 뭔가를 할 수

public static String registration(String url,String data) { 

    Log.e("REGISTRATION:", data); 
    Log.e("REG URL:", url); 

    DefaultHttpClient client = new DefaultHttpClient(); 
    HttpPost postReq = new HttpPost(url); 
    List params = new ArrayList<BasicNameValuePair>(); 
    params.add(new BasicNameValuePair("QueryStr",data)); 
    params.add(new BasicNameValuePair("Action", "REG")); 
    String result = "0"; 
    try { 

     postReq.setEntity(new UrlEncodedFormEntity(params)); 
     HttpResponse resp = client.execute(postReq); 
     if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
      HttpEntity entity = resp.getEntity(); 
      String dt = EntityUtils.toString(entity); 

      Log.e("RESPONSE: ", dt); // returned data from server 

     } else { 

     } 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return result; 

} 
1

당신은이 같은 AsyncTask를 문자열로 매개 변수를 전달할 수 있습니다

new AsyncTack().execute(string1, string2, string3); 

문자열 1, 문자열 2, string3는 doInBackground 방법, 로 전달되며,이처럼 참조 할 수 있습니다 :

@Override 
protected Void doInBackground(String... params){ 
    String s1 = params[0] // the original string1 
    String s2 = params[1] // the original string2 
    String s3 = params[2] // the original string3 
} 

기본적으로 .execute()에 피드하는 모든 것은 doInBackground에 대한 배열로 전달됩니다.

doInBackground 메서드는 백그라운드 스레드에서 실행되므로 안전하게 백그라운드에서 네트워크 작업을 호출 할 수 있습니다. 반환 된 데이터를 사용하여 UI를 업데이트해야하는 경우 AsyncTask를 수정하여 doInBackground 메서드가 String 또는 JSONObject를 반환하도록합니다. 반환 된 데이터는 UI 스레드에서 실행되는 onPostExecute 메서드에 전달되어 UI를 업데이트 할 수 있습니다.

관련 문제