android与服务器通信,连接,Struts2也可以(自用)

本文介绍了一种在Android应用中实现POST请求的方法,并详细展示了如何通过HTTPURLConnection发送JSON格式的数据到服务器,以及服务器端如何解析这些数据并返回响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.connection;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
public class Connection {
public static String encoding="UTF-8";
public static String baseUrl="http://192.168.1.101:8080/";
public static String postData(Context context,Map params,String requestUrl) throws Exception{
String result=null;
String data="";
StringBuffer sb = new StringBuffer();
//组装数据,形如:aaa=admin&bbb=123
// if(params!=null){
// for (Map.Entry entry : params.entrySet()) {
// sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encoding));
// sb.append("&");
// }
// //组装完成的数据
// data = sb.deleteCharAt(sb.length() - 1).toString();
// }
//转换为json样子
if(params!=null){
JSONObject n=new JSONObject(params);
data="data="+URLEncoder.encode(n.toString(),"UTF-8");//特别强调,这里的设置时为了防止乱码
}
//传入请求的路径
URL url = new URL(Connection.baseUrl+requestUrl);
//打开连接
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 设置提交方式
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
// post方式不能使用缓存
httpConn.setUseCaches(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 维持长连接
httpConn.setRequestProperty("Connection", "Keep-Alive");
// 设置浏览器编码
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("contentType", "UTF-8");
httpConn.setRequestProperty("Accept-Charset", "UTF-8");
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
// 将请求参数数据向服务器端发送
dos.writeBytes(data);
dos.flush();
dos.close();
//接受数据的工作
InputStream inputStream=null;
if (httpConn.getResponseCode() == 200) {
// 获得服务器端输出流
inputStream=httpConn.getInputStream();
byte[] reserveData = readStream(inputStream);
result=new String(reserveData);
return result;
}
return null;
}
//通过输入流获得字节数组  
public static byte[] readStream(InputStream is) throws Exception {
byte[] buffer = new byte[1024];  
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len=is.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
is.close();
return bos.toByteArray();
}  
}



服务端处理:
//客户端登陆方法
public ActionForward telUserLoging(HttpServletRequest request,
HttpServletResponse response, ActionMapping mapping)
throws Exception {
this.reserJson=this.reserveJsongData(request);
JSONObject json=new JSONObject();
if(reserJson.get("account").equals("wang")&&reserJson.get("pwd").equals("123")){
json.put("accountId", "success");
}else{
json.put("accountId", "faile");
}
return gotoAndroidClient(request, json);
}
//最后的跳转方法————公用
public ActionForward gotoAndroidClient(HttpServletRequest request,JSONObject json){
request.setAttribute("resultStr", json.toString());
return new ActionForward("/forandroid/result.jsp", false);
}
//最前的接收数据方法————公用
public JSONObject reserveJsongData(HttpServletRequest request){
String data=request.getParameter("data");
return JSONObject.fromObject(data);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值