Android 异步任务中的IOException
我正在尝试使用AsyncTask执行一个简单的Http请求,代码如下:Android 异步任务中的IOException,android,android-asynctask,httprequest,ioexception,Android,Android Asynctask,Httprequest,Ioexception,我正在尝试使用AsyncTask执行一个简单的Http请求,代码如下: public class MainActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
}
public void onClick(View v) {
String url = "http://www.mysamplecode.com/DowloadData";
new MyAsyncTask(this).execute(url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class MyAsyncTask extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private boolean error = false;
private Context mContext;
private int NOTIFICATION_ID = 1;
private Notification mNotification;
private NotificationManager mNotificationManager;
public MyAsyncTask(Context context){
this.mContext = context;
//Get the notification manager
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
protected void onPreExecute() {
createNotification("Data download is in progress","");
}
protected String doInBackground(String... urls) {
String URL = null;
String param1 = "abc";
String param2 = "xyz";
try {
//URL passed to the AsyncTask
URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//Any other parameters you would like to set
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("param1",param1));
nameValuePairs.add(new BasicNameValuePair("param2",param2));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Response from the Http Request
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
//Check the Http Request for success
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
}
else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
error = true;
cancel(true);
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
error = true;
cancel(true);
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();
error = true;
cancel(true);
}
return content;
}
protected void onCancelled() {
createNotification("Error occured during data download", content);
}
protected void onPostExecute(String content) {
if (error) {
createNotification("Data download ended abnormally!",content);
} else {
createNotification("Data download is complete!","");
}
}
private void createNotification(String contentTitle, String contentText) {
//Build the notification using Notification.Builder
Notification.Builder builder = new Notification.Builder(mContext)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setAutoCancel(true)
.setContentTitle(contentTitle)
.setContentText(contentText);
//Get current notification
mNotification = builder.getNotification();
//Show the notification
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
}
}
public类MainActivity扩展活动实现OnClickListener{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
按钮开始=(按钮)findViewById(R.id.button1);
start.setOnClickListener(this);
}
公共void onClick(视图v){
字符串url=”http://www.mysamplecode.com/DowloadData";
新建MyAsyncTask(this).execute(url);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.activity\u主菜单);
返回true;
}
公共类MyAsyncTask扩展了AsyncTask{
私有静态最终整数注册\u超时=3*1000;
私有静态最终整数等待超时=30*1000;
私有最终HttpClient HttpClient=新的DefaultHttpClient();
最终的HttpParams params=httpclient.getParams();
HttpResponse响应;
私有字符串内容=null;
私有布尔错误=false;
私有上下文;
私有int通知_ID=1;
私人通知;
私人通知经理通知经理;
公共MyAsyncTask(上下文){
this.mContext=上下文;
//获取通知管理器
mNotificationManager=(NotificationManager)mContext.getSystemService(Context.NOTIFICATION\u服务);
}
受保护的void onPreExecute(){
createNotification(“正在下载数据”);
}
受保护的字符串doInBackground(字符串…URL){
字符串URL=null;
字符串param1=“abc”;
字符串param2=“xyz”;
试一试{
//传递给异步任务的URL
URL=URL[0];
HttpConnectionParams.setConnectionTimeout(参数,注册超时);
HttpConnectionParams.setSoTimeout(参数,等待超时);
setTimeout(参数,等待超时);
HttpPost HttpPost=新的HttpPost(URL);
//要设置的任何其他参数
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“param1”,param1));
添加(新的BasicNameValuePair(“param2”,param2));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//来自Http请求的响应
response=httpclient.execute(httpPost);
StatusLine StatusLine=response.getStatusLine();
//检查Http请求是否成功
if(statusLine.getStatusCode()==HttpStatus.SC\u OK){
ByteArrayOutputStream out=新建ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content=out.toString();
}
否则{
//关闭连接。
Log.w(“HTTP1:,statusLine.getReasonPhrase());
response.getEntity().getContent().close();
抛出新IOException(statusLine.getReasonPhrase());
}
}捕获(客户端协议例外e){
Log.w(“HTTP2:”,e);
content=e.getMessage();
错误=真;
取消(真);
}捕获(IOE异常){
Log.w(“HTTP3:”,e);
content=e.getMessage();
错误=真;
取消(真);
}捕获(例外e){
Log.w(“HTTP4:”,e);
content=e.getMessage();
错误=真;
取消(真);
}
返回内容;
}
受保护的void onCancelled(){
createNotification(“数据下载时出错”,内容);
}
受保护的void onPostExecute(字符串内容){
如果(错误){
createNotification(“数据下载异常结束!”,内容);
}否则{
createNotification(“数据下载完成!”,“”);
}
}
私有void createNotification(字符串contentTitle、字符串contentText){
//使用notification.Builder生成通知
Notification.Builder=new Notification.Builder(mContext)
.setSmallIcon(android.R.drawable.stat\u系统下载)
.setAutoCancel(真)
.setContentTitle(contentTitle)
.setContentText(contentText);
//获取当前通知
mNotification=builder.getNotification();
//显示通知
mNotificationManager.notify(通知ID,mNotification);
}
}
}
这似乎是可行的,但MyAsyncTask总是给出一个IOException,并调用onCancelled()方法,用错误消息关闭请求,为什么?我怎样才能解决这个问题?
日志(当我捕获异常时附加到参数“content”上)显示消息“Method not allowed”,代码中有错误?可能有点晚,但将URL从“”更改为“”可以处理它。我认为这是一个限制,您在AndroidManifest.xml中指定权限吗?或者您的服务器不可用,这就像服务器端问题一样…是的,我有,所以可能是服务器问题?代码可以吗?我知道
out.close()
不应该有任何效果,但是试着将close()
移动到toString()
之后,我这样做了,但是不起作用……也许我必须尝试连接另一台服务器。这个答案表明,在评论中使用HTTPS而不是HTTP会更好。