Android客户端访问服务器

----------2016年10月16日21:50:54


1、访问网络是耗时操作,放在子线程中执行


new Thread(new Runnable() {
public void run() {
//具体操作。。。。
}
}).start();

2、Get方式请求


//要获取数据的URL地址
String newsPath_url="http://"+服务器IP地址+":"+服务端口号+"/"+项目路径";

//获取一个url对象,通过url对象得到一个urlconnnection对象
URL url = new URL(newsPath_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

//设置连接的方式和超时时间
connection.setRequestMethod("GET");
connection.setConnectTimeout(10*1000);

//获取请求响应码
int code = connection.getResponseCode();

if(code == 200){//请求成功
//获取请求到的流信息
InputStream inputStream = connection.getInputStream();

对流进行操作,获取数据
......
}


3、Post方式请求


post方式比Get多了请求的内容:username=root&password=root

String body = "username="+username+"&password="+password;

//设置UrlConnection可以写请求的内容
openConnection.setDoOutput(true);

//获取一个outputstream,并将内容写入该流
openConnection.getOutputStream().write(body.getBytes());


4、乱码处理
1.客户端发送服务端乱码:
在发送请求时,有时服务端接收到的数据可能是乱码,所以,在请求前统一编码:UTF-8
URLEncoder.encode(username,"utf-8")
2.服务端发客户端乱码:
服务端:
将要发送的数据以utf-8编码方式写入输出流,
response.getOutputStream().write("XXX".getBytes("utf-8"));















  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
作为AI助手,我可以为您提供一些代码示例,但请注意这只是一个简单的模板,实际情况需要根据您的具体需求进行调整。 首先,在Android客户端中,您需要使用HTTP请求从服务器获取数据。以下是一个简单的HTTP请求示例: ```java private class GetDataTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; try { URL url = new URL(urls[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream inputStream = conn.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while (line != null) { line = bufferedReader.readLine(); response += line; } } catch (Exception e) { e.printStackTrace(); } return response; } @Override protected void onPostExecute(String result) { //处理服务器返回的数据 } } ``` 接下来,您需要在服务器端部署您的数据库,并提供API以供客户端调用。以下是一个简单的API示例: ```php <?php //连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //执行SQL查询语句 $sql = "SELECT * FROM MyGuests"; $result = $conn->query($sql); //将查询结果转换为JSON格式并返回给客户端 $rows = array(); while($r = mysqli_fetch_assoc($result)) { $rows[] = $r; } echo json_encode($rows); //关闭数据库连接 $conn->close(); ?> ``` 最后,在Android客户端中调用您的API获取数据: ```java new GetDataTask().execute("http://example.com/api/getData.php"); ``` 以上仅为简单示例,实际情况可能会更加复杂。您需要仔细考虑您的数据结构、安全性、性能等方面,并进行适当的优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值