安卓向服务端发送请求
手机端
开发及运行环境
开发工具:Android Studio 3.3.2,安卓开发包SdkVersion 28,实现功能手机端向服务端请求车辆的位置信息。主线程新建AccessNetwork线程调用GetPostUtil工具类去向服务端发送请求与接受数据,并将数据显示到前端去。
权限请求
因为需要向服务端发送请求并接受服务端发送来的消息,所以app需要请求网络服务的权限。修改
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="club.yzren.iot">
<uses-permission android:name="android.permission.INTERNET"/><!-- 请求网络权限-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Get与Post请求工具类
定义一个工具类,可以向服务端发送Get与Post请求用来对服务端发送请求与接受服务端的响应信息。
类中有两个方法,并且放回值为Json数据。
//url为请求地址 params为请求的参数
public static String sendGet(String url, String params)
public static String sendPost(String url, String params)
其中用到的类
URLConnection
调用set方法设置url,通用连接属性,调用*connect()方法建立连接,最后再使用getHeaderFields()**获取服务端响应的数据。
package club.yzren.iot;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class GetPostUtil
{
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param params
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendGet(String url, String params)
{
String result = "";
BufferedReader in = null;
try
{
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet())
{
System.out.println(key + "--->" + map.get(key));
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL发送POST方法的请求
*
* @param url
* 发送请求的URL
* @param params
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendPost(String url, String params)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}
AccessNetwork
新建一个类AccessNetwork实现Runnable接口,实现手机端的前端页面与后端逻辑处理能整合。
通过向服务端请求数据,并找到前端组件,将服务端响应的数据放到前端显示。
class AccessNetwork implements Runnable{
private String op ;
private String url;
private String params;
private Handler h;
public AccessNetwork(String op, String url, String params,Handler h) {
super();
this.op = op;
this.url = url;
this.params = params;
this.h = h;
}
@Override
public void run() {
JSONObject jsonObject = null;
String nowLongitude = null;
String nowLatitude = null;
String speedValue = "0";
String Temperature = "0";
String result = null;
Message m = new Message();
EditText speed = (EditText) findViewById(R.id.speedValue);
EditText wendu = (EditText) findViewById(R.id.wenduzhi);
EditText gps = (EditText) findViewById(R.id.gps);
m.what = 0x123;
while (true) {
if (op.equals("GET")) {
// Log.i("iiiiiii","发送GET请求");
m.obj = GetPostUtil.sendGet(url, params);
result = GetPostUtil.sendGet(url, params);
//Log.i("iiiiiii",">>>>>>>>>>>>"+m.obj);
}
if (op.equals("POST")) {
Log.i("iiiiiii", "发送POST请求");
m.obj = GetPostUtil.sendPost(url, params);
result = GetPostUtil.sendGet(url, params);
Log.i("gggggggg", ">>>>>>>>>>>>" + m.obj);
}
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (jsonObject != null) {
if (jsonObject.has("Speed"))
speedValue = jsonObject.get("Speed").toString();
if (jsonObject.has("Temperature"))
Temperature = jsonObject.get("Temperature").toString();
if (jsonObject.has("longitude"))
nowLongitude = jsonObject.get("longitude").toString();
if (jsonObject.has("latitude"))
nowLatitude = jsonObject.get("latitude").toString();
}
} catch(JSONException e){
e.printStackTrace();
}
if (carStatus == 1)
listenGps(nowLongitude, nowLatitude);
longitude = nowLongitude;
latitude = nowLatitude;
gps.setText("经度" + longitude + " 纬度" + latitude);
speed.setText(speedValue);
wendu.setText(Temperature);
// h.sendMessage(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
主类
主类新建副线程AccessNetwork并指定url请求。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button getdata;
ImageView carStatus_;
Thread get;
String longitude;
String latitude;
int carStatus=0;//carStatus=0为车未锁 1为车锁住了
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getdata=(Button)findViewById(R.id.getdata);
carStatus_=(ImageView) findViewById(R.id.carStatus);
getdata.setOnClickListener(this);
carStatus_.setOnClickListener(this);
final TextView textView=(TextView)findViewById(R.id.endtitle);
final Handler h = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0x123){
textView.setText(msg.obj.toString());
}
}
};
get=new Thread(new AccessNetwork("GET", "http://123.207.58.192:8080/getCarInfo", null, h));
}
}
运行截图
Linux服务端
服务端就一个简单的springboot项目,向Thingsboard开源框架请求信息。
@RequestMapping("/getAllInfo")
public String getAllInfo() {
return getInfo();
}
public static String getInfo() {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost("http://120.76.57.30:8080/api/auth/login");
StringEntity s=null;
try {
s = new StringEntity("{\"username\":\"liuwq1219@163.com\", \"password\":\"lwq1219\"}");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(s);
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json");
client=HttpClients.createDefault();
try {
response = client.execute(httpPost);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
String result=null;
try {
result = EntityUtils.toString(entity);
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpGet httpGet = new HttpGet("http://120.76.57.30:8080/api/plugins/telemetry/DEVICE/701d53c0-166c-11e9-a4cf-5d1883281505/values/timeseries");
httpGet.addHeader("Content-Type", "application/json");
try {
httpGet.addHeader("X-Authorization", "Bearer "+jsonObject.getString("token"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client = HttpClients.createDefault();
try {
response = client.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
result = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
作者 吴李明