我正在尝试使用AsyncTask进行简单的Http请求,这是代码:
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);
}
}
}
似乎有效,但是MyAsyncTask总是给出IOException,并且调用了onCancelled()方法,并用错误消息关闭请求,为什么?我怎么解决这个问题?日志(当我捕获到异常时附加到参数“ content”)显示消息“不允许使用方法”,代码中有问题吗?
也许有点晚,但是将您的URL从“ http://www.mysamplecode.com/DowloadData”更改为“ https://www.mysamplecode.com/DowloadData”可以解决。