如何在为Android开发时如何在Android
Deprecated AsyncTask Method
The following code snippet demonstrates how to send POST data using the AsyncTask class:
public class CallAPI extends AsyncTask {
public callapi(){
//设置上下文变量(如果需要)
}
@Override
受保护的void onpreexecute(){
super.onpreexecute();
}
@Override
受保护的字符串doinbackground(字符串... params){
字符串urlstring = params [0]; // url呼叫
字符串数据= params [1]; //发布数据
outputStream out = null;
尝试 {
URL URL =新URL(urlstring);
httpurlconnection urlConnection =(httpurlConnection)url.openconnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter Writer = new BufferedWriter(new UppoteStreamWriter(OUT,“ UTF-8”));
writer.write(数据);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch(异常E){
system.out.println(e.getMessage());
}
}
} [2
httpclient httpclient = new defaulthtpclient();
httppost httppost = new httppost(“ http://www.yoursite.com/script.php”);
尝试 {
列表 nameValuepairs = new ArrayList (2);
nameValuepairs.Add(new BasicNameValuePair(“ ID”,“ 12345”));
nameValuepairs.Add(new BasicNameValuePair(“ StringData”,“ Hi”));
httppost.setentity(新的urlencodedformentity(nameValuepairs));
httpresponse响应= httpclient.execute(httppost);
} catch(client prototocolexception e){
// TODO自动生成的捕获块
} catch(ioexception e){
// TODO自动生成的捕获块
}
}