请我知道这段代码有什么问题,如果我尝试拆分,它只会崩溃我的应用程序,但没有分开的代码行我的应用程序运行成功并从我的服务器返回响应“ “这是代码:
protected String doInBackground(String... params) {
String type= params[0];
String login_url="somelink.com/somelink.php";
if(type.equals("login")){
try {
String username= params[1];
String password= params[2];
URL url= new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data=URLEncoder.encode("n", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data+="&" + URLEncoder.encode("p", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
String[] words=result.split("\\|");
StringBuilder ch=new StringBuilder();
ch.append(words[0]);
String check=ch.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return check;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
答案 0 :(得分:0)
我能看到的唯一显而易见的事情是你可能正在访问一个不存在的元素。这一行:
ch.append(words[0]);
在某些情况下,words
数组的长度可能为零(例如,因为line
为空等等),并且您尝试访问不存在的数组元件。
您需要做的就是添加if
语句,以便在执行words[0]
之前检查是否有非空数组。