首先加入发送请求的类InternetRequest,随便放在一个包里。
package com.example.administrator.xhello;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class InternetRequest {
//参数列表 <键-值>
private HashMap<String, String> stringMap;
public InternetRequest() {
stringMap = new HashMap<String, String>();
}
public void addPara(String key, String value) {
stringMap.put(key, value);
}
//发送请求函数
public String requestPost(String baseUrl) {
StringBuilder tempParams = new StringBuilder();
int pos = 0;
try {
for (String key : stringMap.keySet()) {
if (pos > 0) {
tempParams.append("&");
}
tempParams.append(String.format("%s=%s", key, URLEncoder.encode(stringMap.get(key), "utf-8")));
pos++;
}
String s = tempParams.toString();
//获取网络上get方式提交的整个路径
URL url=new URL(baseUrl);
//打开网络连接
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
//设置提交方式
conn.setRequestMethod("POST");
//设置网络超时时间
conn.setConnectTimeout(5000);
//获取请求头
conn.setRequestProperty("Content-Length",s.length()+"");//键是固定的
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//键和值是固定的
//设置允许对外输出数据
conn.setDoOutput(true);
//把界面上的所有数据写出去
OutputStream os=conn.getOutputStream();
os.write(s.getBytes());
if(conn.getResponseCode()==200){
//用io流与web后台进行数据交互
// InputStream is=conn.getInputStream();
//字节流转字符流
// BufferedReader br=new BufferedReader(new InputStreamReader(is));
//读出每一行的数据
// String str=br.readLine();
//返回读出的每一行的数据
String result = streamToString(conn.getInputStream());
return result;
// Log.e(TAG, "Post方式请求成功,result--->" + result);
}
return "XXX";
} catch (Exception e) {
e.printStackTrace();
return e.getStackTrace().toString();
}
}
public String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
接下来测试注册功能
activity_main.xml代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名:"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码:"/>
<EditText
android:id="@+id/telephone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号:"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="register"
android:text="注册" />
<TextView
android:id="@+id/txtshow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.30" />
</LinearLayout>
页面显示
MainActivity.java代码
package com.example.administrator.xhello;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
String TAG = MainActivity.class.getCanonicalName();
private TextView txtshow;
//接受页面文本用于填充参数列表
private EditText name;
private EditText password;
private EditText telephone;
//加入一个发送请求的IR
private InternetRequest IR;
//加入一个接受响应结果的result
private String result;
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
txtshow.setText(result);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
telephone = (EditText) findViewById(R.id.telephone);
txtshow = (TextView) findViewById(R.id.txtshow);
//创建请求对象
IR = new InternetRequest();
}
public void register(View view) {
//将发送请求所需参数添加进参数列表
IR.addPara("name", name.getText().toString());
IR.addPara("password", password.getText().toString());
IR.addPara("telephone", telephone.getText().toString());
IR.addPara("birthday", " ");
IR.addPara("age", " ");
IR.addPara("sex", " ");
IR.addPara("job", " ");
IR.addPara("email", " ");
//因为主线程不能进行网络请求,所以另建一个线程进行请求
new Thread(postRun).start();
}
//请求线程
Runnable postRun = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
//发送对应请求,每个功能都有对应的url
// result用于接收传回的数据,一般为json形式,如果有特殊需要也可以进行更改
result = IR.requestPost("url");
Log.e(TAG, "Result:"+result);
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}catch (Exception e){
Log.e(TAG, "Exception:"+e.getStackTrace().toString());
}
}
};
}
登录测试
activity_main.xml代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="@+id/telephone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号:"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码:"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="login"
android:text="登录" />
<TextView
android:id="@+id/txtshow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.30" />
</LinearLayout>
页面显示
MainActivity.java代码
package com.example.administrator.xhello;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
String TAG = MainActivity.class.getCanonicalName();
private TextView txtshow;
//接受页面文本用于填充参数列表
private EditText telephone;
private EditText password;
//加入一个发送请求的IR
private InternetRequest IR;
//加入一个接受响应结果的result
private String result;
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
txtshow.setText(result);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
telephone = (EditText) findViewById(R.id.telephone);
password = (EditText) findViewById(R.id.password);
txtshow = (TextView) findViewById(R.id.txtshow);
//创建请求对象
IR = new InternetRequest();
}
public void login(View view) {
//将发送请求所需参数添加进参数列表
IR.addPara("telephone", telephone.getText().toString());
IR.addPara("password", password.getText().toString());
//因为主线程不能进行网络请求,所以另建一个线程进行请求
new Thread(postRun).start();
}
//请求线程
Runnable postRun = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
//发送对应请求,每个功能都有对应的url
// result用于接收传回的数据,一般为json形式,如果有特殊需要也可以进行更改
result = IR.requestPost("url");
Log.e(TAG, "Result:"+result);
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}catch (Exception e){
Log.e(TAG, "Exception:"+e.getStackTrace().toString());
}
}
};
}
调用其它接口主要需要修改的地方,只有按钮点击响应函数中(这次测试用的是android:onClick方式,响应函数为MainActivity.java中的register和login)添加参数的部分,请求需要什么参数就添加什么
以及postRun中的url