我有此代码,但响应Toast
为空谁能告诉我是什么问题?我也不知道如何获得响应代码
谢谢
register_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONTask().execute(main_url);
}
});
public class JSONTask extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url = new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
connection.connect();
InputStream is;
if (responseCode>=200&&responseCode<400){
is = connection.getInputStream();
}else{
is = connection.getErrorStream();
}
reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=reader.readLine()) != null){
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (connection != null){
connection.disconnect();
}
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
}
}
您的connection.connect();用getresponsecode方法完成连接是没有用的。此外,检查您的responseCode的值(如果它小于200,您将获得NullPointerException)
@Override
protected String doInBackground(String... params) {
return null; //Remove this line and replace with below
return stringBuilder.toString();
}