我正在尝试使用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”)显示消息“Method not allowed”,代码中有错误吗?
答案 0 :(得分:-1)
也许有点晚了,但是将URL从“ http://www.mysamplecode.com/DowloadData”更改为“ https://www.mysamplecode.com/DowloadData”可以解决此问题。