好吧,这段代码在 java 中运行良好,但是当我开始在 Android 4.0 模拟器上运行它时它崩溃了。在调试时我注意到它在 httpConn.connect(); 上崩溃了。线
public class GetStringFromUrl {
public static String getString(String urlPageAdress) throws Exception
{
URL url = new URL(urlPageAdress);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Accept-Encoding", "UTF-8");
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect(); //crashes on this line dunno know why
InputStream in = null;
if (httpConn.getContentEncoding() != null && httpConn.getContentEncoding().toString().contains("gzip")) {
in = new GZIPInputStream(httpConn.getInputStream());
} else {
in = httpConn.getInputStream();
}
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(1000);
int read = 0;
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1) {
break;
}
baf.append(buffer, 0, read);
}
String body = new String(baf.toByteArray());
return body;
} }
方法用于 Main Activity
公共类 MainActivity 扩展 Activity{
ToggleButton toogleButton;
public final static String EXTRA_MESSAGE = "ru.kazartsevaa.table.MESSAGE";
int upDown;
int SpinnerCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upDown=0;
setContentView(R.layout.activity_main);
}
public void onClick(View v) 抛出异常 { System.out.print(SpinnerCount); // if(upDown==0) //0 - вылет 1 прилет //{ switch (v.getId()) { case R.id.UpDownButton: { //toogleButton = (ToggleButton) findViewById(R.id.UpDownButton ); // toogleButton.setOnCheckedChangeListener(this); } case R.id.SheremetievoButton: { Spinner SherSpinner = (Spinner) findViewById(R.id.SheremetievoSpinner);
String SpinnerCount= SherSpinner.getItemAtPosition(SherSpinner.getSelectedItemPosition()).toString();
System.out.print(SpinnerCount);
new Thread(){ public void run() {
try {
String body = GetStringFromUrl.getString("www.xyz.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }.start();
int crowd;
}
}
注意:更改为新线程后,它停止崩溃但仍然写入