最近要搞一个安卓项目,于是学了一波安卓的前后端分离,代码参考的菜鸟教程,改进了一下,在页面类中组装好url地址,使PostUtils能够实现复用。
String UpdateAsset_URL = "http://192.168.123.123:8080/updateAsset";//调用的方法接口
new Thread(){
public void run() {
try {
//取得参数
String data = "";//添加传递的参数
result = PostUtils.MainPost(data,UpdateAsset_URL);//获得返回值
handler.sendEmptyMessage(0x123);//toast弹窗
//添加逻辑部分
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
页面代码:
public class LoginActivity extends AppCompatActivity {
//这里填写个人的主机号
private final static String LOGIN_URL = "http://192.168.123.123:8080/ServletForPost";
private String result = "";
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
};
};
@BindView(R.id.et_user_name)
EditText mUsername;
@BindView(R.id.et_pwd)
EditText mPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
}
@OnClick(R.id.btn_login)
public void onViewClicked(){
new Thread(){
public void run() {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
try {
String data = "i="+ URLEncoder.encode(username, "UTF-8")+
"&j="+ URLEncoder.encode(password, "UTF-8");
result = PostUtils.MainPost(data,LOGIN_URL);
handler.sendEmptyMessage(0x123);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
PostUtils:
public class PostUtils {
public static String MainPost(String data,String url)
{
String msg = "1";
try{
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
//设置请求方式,请求超时信息
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//设置运行输入,输出:
conn.setDoOutput(true);
conn.setDoInput(true);
//Post方式不能缓存,需手动设置为false
conn.setUseCaches(false);
//获取输出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
msg = new String(message.toByteArray());
return msg;
}
}catch(Exception e){e.printStackTrace();}
return msg;
}
}
网友评论