当前位置:   article > 正文

Android接口调用_android获取不同按钮调用不同接口

android获取不同按钮调用不同接口

首先加入发送请求的类InternetRequest,随便放在一个包里。

  1. package com.example.administrator.xhello;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLEncoder;
  8. import java.util.HashMap;
  9. public class InternetRequest {
  10. //参数列表 <键-值>
  11. private HashMap<String, String> stringMap;
  12. public InternetRequest() {
  13. stringMap = new HashMap<String, String>();
  14. }
  15. public void addPara(String key, String value) {
  16. stringMap.put(key, value);
  17. }
  18. //发送请求函数
  19. public String requestPost(String baseUrl) {
  20. StringBuilder tempParams = new StringBuilder();
  21. int pos = 0;
  22. try {
  23. for (String key : stringMap.keySet()) {
  24. if (pos > 0) {
  25. tempParams.append("&");
  26. }
  27. tempParams.append(String.format("%s=%s", key, URLEncoder.encode(stringMap.get(key), "utf-8")));
  28. pos++;
  29. }
  30. String s = tempParams.toString();
  31. //获取网络上get方式提交的整个路径
  32. URL url=new URL(baseUrl);
  33. //打开网络连接
  34. HttpURLConnection conn= (HttpURLConnection) url.openConnection();
  35. //设置提交方式
  36. conn.setRequestMethod("POST");
  37. //设置网络超时时间
  38. conn.setConnectTimeout(5000);
  39. //获取请求头
  40. conn.setRequestProperty("Content-Length",s.length()+"");//键是固定的
  41. conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//键和值是固定的
  42. //设置允许对外输出数据
  43. conn.setDoOutput(true);
  44. //把界面上的所有数据写出去
  45. OutputStream os=conn.getOutputStream();
  46. os.write(s.getBytes());
  47. if(conn.getResponseCode()==200){
  48. //用io流与web后台进行数据交互
  49. // InputStream is=conn.getInputStream();
  50. //字节流转字符流
  51. // BufferedReader br=new BufferedReader(new InputStreamReader(is));
  52. //读出每一行的数据
  53. // String str=br.readLine();
  54. //返回读出的每一行的数据
  55. String result = streamToString(conn.getInputStream());
  56. return result;
  57. // Log.e(TAG, "Post方式请求成功,result--->" + result);
  58. }
  59. return "XXX";
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. return e.getStackTrace().toString();
  63. }
  64. }
  65. public String streamToString(InputStream is) {
  66. try {
  67. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  68. byte[] buffer = new byte[1024];
  69. int len = 0;
  70. while ((len = is.read(buffer)) != -1) {
  71. baos.write(buffer, 0, len);
  72. }
  73. baos.close();
  74. is.close();
  75. byte[] byteArray = baos.toByteArray();
  76. return new String(byteArray);
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. return null;
  80. }
  81. }
  82. }

 

接下来测试注册功能

activity_main.xml代码

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical"
  5. android:weightSum="1">
  6. <EditText
  7. android:id="@+id/name"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:hint="请输入用户名:"/>
  11. <EditText
  12. android:id="@+id/password"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:hint="请输入密码:"/>
  16. <EditText
  17. android:id="@+id/telephone"
  18. android:layout_width="match_parent"
  19. android:layout_height="wrap_content"
  20. android:hint="请输入手机号:"/>
  21. <Button
  22. android:layout_width="match_parent"
  23. android:layout_height="wrap_content"
  24. android:onClick="register"
  25. android:text="注册" />
  26. <TextView
  27. android:id="@+id/txtshow"
  28. android:layout_width="match_parent"
  29. android:layout_height="wrap_content"
  30. android:layout_weight="0.30" />
  31. </LinearLayout>

页面显示

MainActivity.java代码

  1. package com.example.administrator.xhello;
  2. import android.os.Bundle;
  3. import android.os.Handler;
  4. import android.os.Message;
  5. import android.os.StrictMode;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.TextView;
  11. import java.io.BufferedReader;
  12. import java.io.BufferedWriter;
  13. import java.io.IOException;
  14. import java.io.InputStreamReader;
  15. import java.io.OutputStreamWriter;
  16. import java.io.PrintWriter;
  17. import java.net.Socket;
  18. import androidx.appcompat.app.AppCompatActivity;
  19. public class MainActivity extends AppCompatActivity {
  20. String TAG = MainActivity.class.getCanonicalName();
  21. private TextView txtshow;
  22. //接受页面文本用于填充参数列表
  23. private EditText name;
  24. private EditText password;
  25. private EditText telephone;
  26. //加入一个发送请求的IR
  27. private InternetRequest IR;
  28. //加入一个接受响应结果的result
  29. private String result;
  30. public Handler handler = new Handler() {
  31. public void handleMessage(Message msg) {
  32. if (msg.what == 1) {
  33. txtshow.setText(result);
  34. }
  35. };
  36. };
  37. @Override
  38. protected void onCreate(Bundle savedInstanceState) {
  39. super.onCreate(savedInstanceState);
  40. setContentView(R.layout.activity_main);
  41. name = (EditText) findViewById(R.id.name);
  42. password = (EditText) findViewById(R.id.password);
  43. telephone = (EditText) findViewById(R.id.telephone);
  44. txtshow = (TextView) findViewById(R.id.txtshow);
  45. //创建请求对象
  46. IR = new InternetRequest();
  47. }
  48. public void register(View view) {
  49. //将发送请求所需参数添加进参数列表
  50. IR.addPara("name", name.getText().toString());
  51. IR.addPara("password", password.getText().toString());
  52. IR.addPara("telephone", telephone.getText().toString());
  53. IR.addPara("birthday", " ");
  54. IR.addPara("age", " ");
  55. IR.addPara("sex", " ");
  56. IR.addPara("job", " ");
  57. IR.addPara("email", " ");
  58. //因为主线程不能进行网络请求,所以另建一个线程进行请求
  59. new Thread(postRun).start();
  60. }
  61. //请求线程
  62. Runnable postRun = new Runnable() {
  63. @Override
  64. public void run() {
  65. // TODO Auto-generated method stub
  66. try {
  67. //发送对应请求,每个功能都有对应的url
  68. // result用于接收传回的数据,一般为json形式,如果有特殊需要也可以进行更改
  69. result = IR.requestPost("url");
  70. Log.e(TAG, "Result:"+result);
  71. Message message = new Message();
  72. message.what = 1;
  73. handler.sendMessage(message);
  74. }catch (Exception e){
  75. Log.e(TAG, "Exception:"+e.getStackTrace().toString());
  76. }
  77. }
  78. };
  79. }

 

登录测试

activity_main.xml代码

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical"
  5. android:weightSum="1">
  6. <EditText
  7. android:id="@+id/telephone"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:hint="请输入手机号:"/>
  11. <EditText
  12. android:id="@+id/password"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:hint="请输入密码:"/>
  16. <Button
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:onClick="login"
  20. android:text="登录" />
  21. <TextView
  22. android:id="@+id/txtshow"
  23. android:layout_width="match_parent"
  24. android:layout_height="wrap_content"
  25. android:layout_weight="0.30" />
  26. </LinearLayout>

页面显示

MainActivity.java代码

  1. package com.example.administrator.xhello;
  2. import android.os.Bundle;
  3. import android.os.Handler;
  4. import android.os.Message;
  5. import android.os.StrictMode;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.TextView;
  11. import java.io.BufferedReader;
  12. import java.io.BufferedWriter;
  13. import java.io.IOException;
  14. import java.io.InputStreamReader;
  15. import java.io.OutputStreamWriter;
  16. import java.io.PrintWriter;
  17. import java.net.Socket;
  18. import androidx.appcompat.app.AppCompatActivity;
  19. public class MainActivity extends AppCompatActivity {
  20. String TAG = MainActivity.class.getCanonicalName();
  21. private TextView txtshow;
  22. //接受页面文本用于填充参数列表
  23. private EditText telephone;
  24. private EditText password;
  25. //加入一个发送请求的IR
  26. private InternetRequest IR;
  27. //加入一个接受响应结果的result
  28. private String result;
  29. public Handler handler = new Handler() {
  30. public void handleMessage(Message msg) {
  31. if (msg.what == 1) {
  32. txtshow.setText(result);
  33. }
  34. };
  35. };
  36. @Override
  37. protected void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.activity_main);
  40. telephone = (EditText) findViewById(R.id.telephone);
  41. password = (EditText) findViewById(R.id.password);
  42. txtshow = (TextView) findViewById(R.id.txtshow);
  43. //创建请求对象
  44. IR = new InternetRequest();
  45. }
  46. public void login(View view) {
  47. //将发送请求所需参数添加进参数列表
  48. IR.addPara("telephone", telephone.getText().toString());
  49. IR.addPara("password", password.getText().toString());
  50. //因为主线程不能进行网络请求,所以另建一个线程进行请求
  51. new Thread(postRun).start();
  52. }
  53. //请求线程
  54. Runnable postRun = new Runnable() {
  55. @Override
  56. public void run() {
  57. // TODO Auto-generated method stub
  58. try {
  59. //发送对应请求,每个功能都有对应的url
  60. // result用于接收传回的数据,一般为json形式,如果有特殊需要也可以进行更改
  61. result = IR.requestPost("url");
  62. Log.e(TAG, "Result:"+result);
  63. Message message = new Message();
  64. message.what = 1;
  65. handler.sendMessage(message);
  66. }catch (Exception e){
  67. Log.e(TAG, "Exception:"+e.getStackTrace().toString());
  68. }
  69. }
  70. };
  71. }

 

调用其它接口主要需要修改的地方,只有按钮点击响应函数中(这次测试用的是android:onClick方式,响应函数为MainActivity.java中的register和login)添加参数的部分,请求需要什么参数就添加什么

以及postRun中的url

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号