-1

旨在通过远程服务器尝试处理 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 版本上正常工作?

4

1 回答 1

1

您可能正在尝试在 UI 线程上执行网络操作,请将您的网络相关操作移至后台线程,最好是 AsyncTask,请参阅此示例以了解如何正确执行

于 2013-03-26T16:17:59.673 回答