Android点击按钮发送请求,上点击按钮,Android的HTTP POST请求(Android HTTP post reques

本文详细介绍了如何在Android应用中通过按钮点击触发一个HTTP POST请求,包括使用AsyncTask处理网络操作,展示了如何设置HttpClient、HttpPost以及参数传递。适合初学者理解HTTP请求的实践应用。
摘要由CSDN通过智能技术生成

我想通过点击按钮来我的网站发送一个HTTP POST请求。 我搜索只配发发现这一段代码

// Create a new HttpClient and Post Header

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {

// Add your data

List nameValuePairs = new ArrayList(2);

nameValuePairs.add(new BasicNameValuePair("id", "12345"));

nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request

HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

} catch (IOException e) {

// TODO Auto-generated catch block

}

但我不知道它是如何与按钮的点击工作。

Answer 1:

使用的AsyncTask对按钮点击执行网络Opertion为:

public class onbuttonclickHttpPost extends AsyncTask {

@Override

protected String doInBackground(String... params) {

byte[] result = null;

String str = "";

// Create a new HttpClient and Post Header

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {

// Add your data

List nameValuePairs = new ArrayList(2);

nameValuePairs.add(new BasicNameValuePair("id", "12345"));

nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request

HttpResponse response = httpclient.execute(httppost);

StatusLine statusLine = response.getStatusLine();

if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){

result = EntityUtils.toByteArray(response.getEntity());

str = new String(result, "UTF-8");

}

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

} catch (IOException e) {

// TODO Auto-generated catch block

}

return str;

}

/**

* on getting result

*/

@Override

protected void onPostExecute(String result) {

// something with data retrieved from server in doInBackground

}

}

和按钮单击开始的AsyncTask onbuttonclickHttpPost为:

buttonclick.setOnClickListener(new View.OnClickListener()

{

public void onClick(View v) {

new onbuttonclickHttpPost.execute(null);

}

});

Answer 2:

试试这个...从我工作的项目

我已经使用Thread和NameValuePair执行该.....

public String postData(String url, String xmlQuery) {

final String urlStr = url;

final String xmlStr = xmlQuery;

final StringBuilder sb = new StringBuilder();

Thread t1 = new Thread(new Runnable() {

public void run() {

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(urlStr);

try {

List nameValuePairs = new ArrayList(

1);

nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

Log.d("Vivek", response.toString());

HttpEntity entity = response.getEntity();

InputStream i = entity.getContent();

Log.d("Vivek", i.toString());

InputStreamReader isr = new InputStreamReader(i);

BufferedReader br = new BufferedReader(isr);

String s = null;

while ((s = br.readLine()) != null) {

Log.d("YumZing", s);

sb.append(s);

}

Log.d("Check Now", sb + "");

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} /*

* catch (ParserConfigurationException e) { // TODO

* Auto-generated catch block e.printStackTrace(); } catch

* (SAXException e) { // TODO Auto-generated catch block

* e.printStackTrace(); }

*/

}

});

t1.start();

try {

t1.join();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("Getting from Post Data Method " + sb.toString());

return sb.toString();

}

文章来源: Android HTTP post request on clicking button

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 创建Model层:创建一个接口用于定义网络请求的方法,例如: ``` public interface LoginModel { void login(String username, String password, String code, Callback callback); } ``` 2. 创建Presenter层:创建一个Presenter类,用于处理业务逻辑和网络请求,例如: ``` public class LoginPresenter { private LoginModel loginModel; public LoginPresenter(LoginModel loginModel) { this.loginModel = loginModel; } public void login(String username, String password, String code) { loginModel.login(username, password, code, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { // 处理网络请求成功的逻辑 } @Override public void onFailure(Call call, IOException e) { // 处理网络请求失败的逻辑 } }); } } ``` 3. 创建View层:创建一个Activity或Fragment作为View层,用于处理用户界面和Presenter层的交互,例如: ``` public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private EditText etUsername; private EditText etPassword; private EditText etCode; private ImageView ivCode; private Button btnLogin; private LoginPresenter loginPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); etUsername = findViewById(R.id.et_username); etPassword = findViewById(R.id.et_password); etCode = findViewById(R.id.et_code); ivCode = findViewById(R.id.iv_code); btnLogin = findViewById(R.id.btn_login); loginPresenter = new LoginPresenter(new LoginModelImpl()); ivCode.setOnClickListener(this); btnLogin.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_code: // 更新验证码图片 break; case R.id.btn_login: String username = etUsername.getText().toString().trim(); String password = etPassword.getText().toString().trim(); String code = etCode.getText().toString().trim(); loginPresenter.login(username, password, code); break; } } } ``` 4. 创建Model层实现类:创建一个实现了LoginModel接口的类,用于实现网络请求的具体逻辑,例如: ``` public class LoginModelImpl implements LoginModel { @Override public void login(String username, String password, String code, Callback callback) { OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("username", username) .add("password", password) .add("code", code) .build(); Request request = new Request.Builder() .url("http://example.com/login") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(callback); } } ``` 5. 在AndroidManifest.xml文件中添加网络访问权限: ``` <uses-permission android:name="android.permission.INTERNET"/> ``` 6. 编译运行程序,在登录界面输入账号、密码和验证码,点击登录按钮,Presenter层会发起网络请求,Model层实现类会执行具体的网络请求逻辑,请求结果会回调到Presenter层的Callback中,在Callback中处理网络请求的成功或失败逻辑。在View层中更新界面的显示效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值