2013-03-26 39 views
-1

目標努力的過程HTTP POST通過遠程服務器應用在HTTP POST過程中關閉用戶登錄信息

我的代碼工作良好2.3.3但4.1和4.2的應用程序強制關閉

我AndroidManifest。 XML文件具有

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="17" 
    android:maxSdkVersion="17" /> 

並使用HTTP POST方法的代碼的目標是

public class postdata { 
public static final String Logger = postdata.class.getName(); 
private static String slurp(InputStream in) throws IOException { 
    StringBuffer out = new StringBuffer(); 
     byte[] b = new byte[4096]; 
     for (int n; (n = in.read(b)) != -1;) { 
      out.append(new String(b, 0, n)); 
     } 
    return out.toString(); 
} 
public static String post_string(String url, String urlParameters) throws IOException { 
HttpURLConnection conn = null; 
    try { 
    conn = (HttpURLConnection) new URL(url).openConnection(); 
    } catch (MalformedURLException e) { 
    Log.e(Logger, "MalformedURLException While Creating URL Connection - " + e.getMessage()); 
    throw e; 
    } catch (IOException e) { 
    Log.e(Logger, "IOException While Creating URL Connection - " + e.getMessage()); 
    throw e; 
} 
    conn.setDoOutput(true); 
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.length())); 
    OutputStream os = null; 
    try { 
     os = conn.getOutputStream(); 
    } catch (IOException e) { 
    Log.e(Logger, "IOException While Creating URL OutputStream - " + e.getMessage()); 
    throw e; 
    } 
    try { 
     os.write(urlParameters.toString().getBytes()); 
    } catch (IOException e) { 
    Log.e(Logger, "IOException While writting URL OutputStream - " + e.getMessage()); 
    throw e; 
    } 
    InputStream in = null; 
    try { 
     in = conn.getInputStream(); 
    } catch (IOException e) { 
    Log.e(Logger, "IOException While Creating URL InputStream - " + e.getMessage()); 
    throw e; 
    } 
    String output = null; 
    try { 
     output = slurp(in); 
    } catch (IOException e) { 
     Log.e(Logger, "IOException While Reading URL OutputStream - " + e.getMessage()); 
     throw e; 
    } finally { 
    try { 
     os.close(); 
     in.close(); 
     } catch (IOException e) { 
     Log.e(Logger, "IOException While Closing URL Output and Input Stream - " + e.getMessage()); 
    } 
    } 
conn.disconnect();return output; 
} 
} 

如何讓我的代碼在所有的android版本上都能正常工作?

+0

發佈logcat – 2013-03-26 16:13:27

+0

請發表LogCat報告 – 2013-03-26 16:14:08

+0

還有一個初學者如何獲得logCat? – 2013-03-26 16:17:03

回答

1

您可能試圖在UI線程上執行網絡操作,請將您的網絡相關操作移至後臺線程,最好是AsyncTask,see this example on how to do it correctly

+0

我的代碼工作將在Android 2.3.3,但在Android 4.1或4.2其自動關閉不工作,當我嘗試http發佈任何數據 – 2013-03-26 16:28:06

+0

是的,它會在4.1和以上的設備上失敗,因爲嚴格模式默認啓用,請參閱http ://developer.android.com/reference/android/os/NetworkOnMainThreadException.html – 2013-03-26 16:30:54

+0

沒問題,謝謝你,但有沒有任何準備好的功能或類我可以使用?目標仍然是一個初學者,所以它看起來很難對我 – 2013-03-26 16:38:53