我有送籤這個代碼的請求:的Android異步HttpURLConnection的要求
@Override
public void onClick(View arg0) {
switch(arg0.getId()) {
case R.id.signInButton:
new AsyncSignIn().execute();
break;
default:
break;
}
}
private class AsyncSignIn extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void...voids) {
try {
String email = eField.getText().toString();
String password = pField.getText().toString();
if(isOnline(getApplicationContext())) {
if(!Requester.signIn(email, password)) {
makeToast("Неверный логин или пароль.");
}
else {
_userEmail = email;
startMainContentActivity();
}
}
else {
makeToast("Нет доступа к интернету.");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
但應用程序崩潰與NetworkOnMainThread例外:
01-24 20:04:15.248: E/AndroidRuntime(758): android.os.NetworkOnMainThreadException
其實在這個字符串中的「把柄」被一個HttpURLConnection對象:
DataOutputStream writer = new DataOutputStream(handle.getOutputStream());
我已經嘗試過使用Handler來做這件事, e是同樣的結果。怎麼了?
更新
這是發送POST請求登錄的函數:從清單
protected String sendPost(String _url, String _urlParameters) throws IOException {
URL url = new URL(_url);
HttpURLConnection handle = (HttpURLConnection) url.openConnection();
handle.setRequestMethod("POST");
handle.setRequestProperty("Host", Host);
handle.setRequestProperty("Content-Type", POSTContentType);
handle.setRequestProperty("Content-Length", ""+_urlParameters.getBytes().length);
handle.setRequestProperty("User-Agent", UserAgent);
handle.setRequestProperty("Accept", Accept);
handle.setRequestProperty("Accept-Language", AcceptLang);
handle.setRequestProperty("Connection", Connection);
handle.setUseCaches(false);
handle.setDoOutput(true);
handle.setDoInput(true);
DataOutputStream writer = new DataOutputStream(handle.getOutputStream()); //App crashed string
writer.writeBytes(_urlParameters);
writer.flush();
writer.close();
int responseCode = handle.getResponseCode();
if(responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(handle.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
return response.toString();
}
else {
return null;
}
}
權限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>
登入
它沒有任何有趣的地方。
public boolean signIn(String _email, String _pass) throws IOException {
String link = signInURL;
String signInData = "email="+_email+"&password="+_pass;
String response = sendPost(link, signInData);
System.out.println(response);
if(response.compareTo("Logged") == 0) {
return true;
}
return false;
}
makeToast
與makeToast一樣的 - 什麼有趣的。
protected void makeToast(String mess) {
Toast t = Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
。你有這個權限清單文件。 –
InnocentKiller
是的,而且還有一個權限 uses-permission> –
請,發佈網絡訪問代碼片段 – sthor69