irpas技术客

Android通过okhttp向后台(springboot)发送get和post请求_~浮生~_android发送请求

网络 2549

首先,将项目结构调整为android 找到AndroidManifest.xml 在其中添加访问网络的权限

<uses-permission android:name="android.permission.INTERNET"/>

然后,找到build.gradle文件,后面有.app的那个 在其中引入okhttp

implementation 'com.squareup.okhttp3:okhttp:3.8.1'

第一种,Get 请求:

String url="http://192.168.125.173:8080/android/loginDispose"; OkHttpClient client=new OkHttpClient(); final Request request=new Request.Builder() .url(url) .get() .build(); Call call=client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e){ Log.d(TAG,"请求失败:"+e); } @Override public void onResponse(Call call, Response response){ // 请求成功后的回调方法,后台返回的数据从response中获得 } });

第二种,Post请求:

String url="http://192.168.125.173:8080/android/selectShopping"; OkHttpClient okHttpClient = new OkHttpClient(); FormBody formBody = new FormBody.Builder() .add("loginUserPhone",loginUserPhone).build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Call call=okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG,"请求失败:"+e); } @Override public void onResponse(Call call, Response response) throws IOException { String str =response.body().string(); } });

我们用Post请求来举例: 上述Post代码向后台发送了一个String数据 后台使用springboot框架,定义一个相同的参数来接收来自android发送的数据,代码如下 后台打印结果如下: android请求成功后,后台返回请求的数据,android通过onResponse方法处理回调的数据,打印结果如下:

Log.i("请求返回的数据:",response.body().string());

这样android发送post请求,后台返回数据就都成功了,但也存在一个问题。

如果我发送的post请求携带多个数据,那么后台方法的参数就会非常多,通常我们会将这些数据放到map中 android的代码如下:

String url="http://192.168.125.173:8080/android/loginDispose"; // 存储登录用户的数据 Map<String,String> map=new HashMap<>(); map.put("phone", String.valueOf(phone.getText())); map.put("password", String.valueOf(password.getText())); // 将map转换为json对象 JSONObject json=new JSONObject(map); OkHttpClient okHttpClient = new OkHttpClient(); FormBody formBody = new FormBody.Builder().add("map", String.valueOf(json)).build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Call call=okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(context, "服务器错误!", Toast.LENGTH_LONG).show(); } @Override public void onResponse(Call call, Response response) throws IOException { String str=response.body().string(); } }); return mark;

后台接收到android发送的map,后台代码如下: android要发送的用户名和密码,首先被放入map中,然后将map转为JSONObject,最后将json对象转变为String发送到后台

后台通过@RequestParam注解来获得传递的String,new一个Gson对象,通过Gson将String转变为Map

后台打印结果如下: 到此,发送携带多个数据的post请求就完成了,但是还存在一个问题。 如果android向后台发送了一个Post请求,后台返回了一个对象数组,android该怎样处理?

首先,后台的数据库中存在一张product表,并建立了一个与之对应的实体Product类 Product类的代码如下:

public class Product implements Serializable { private String uuid; private String phone; private String name; private BigDecimal price; private String description; private String picturespath; private String category; private Date time; private String status; // 一个商品对应多个购物车 private List<Shopping> shoppingList; public Product(String uuid, String phone, String name, BigDecimal price, String description, String picturespath, String category, Date time, String status) { this.uuid = uuid; this.phone = phone; this.name = name; this.price = price; this.description = description; this.picturespath = picturespath; this.category = category; this.time = time; this.status = status; } public Product() { super(); } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicturespath() { return picturespath; } public void setPicturespath(String picturespath) { this.picturespath = picturespath; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<Shopping> getShoppingList() { return shoppingList; } public void setShoppingList(List<Shopping> shoppingList) { this.shoppingList = shoppingList; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", uuid=").append(uuid); sb.append(", phone=").append(phone); sb.append(", name=").append(name); sb.append(", price=").append(price); sb.append(", description=").append(description); sb.append(", picturespath=").append(picturespath); sb.append(", category=").append(category); sb.append(", time=").append(time); sb.append(", status=").append(status); sb.append(", shoppingList=").append(shoppingList); sb.append("]"); return sb.toString(); } }

android将请求后台product表的所有数据,后台使用MyBatis作为持久层框架,代码如下: 打印结果如下:

android的代码和打印结果如下:

从两次打印结果看,从数据库中获得的数据被转换为JSON格式发送到了android,这是因为@ResponseBody注解的原因

android拿到了JSON格式的数据后做如下处理: (1)将String转换为JSONArray,JSONArray中的每一个成员都是一个Product对象,所以要在android也建立一个Product类 (2)将JSONArray的每个成员都转换为JSONObject (3)将JSONObject转换为Product实体类

具体代码如下:

String str =response.body().string(); Gson gson=new Gson(); Product product=new Product(); try { // 将字符串转换为json数组 JSONArray jsonArray=new JSONArray(str); for(int i=0;i<jsonArray.length();i++){ // 将Json数组中的元素,拿出来转换成Json对象 JSONObject jsonObject=(JSONObject) jsonArray.get(i); // 将Json对象转换成实体对象,并加入数组 product=gson.fromJson(String.valueOf(jsonObject),Product.class); productList.add(product); } } catch (JSONException e) { e.printStackTrace(); }

这里用到了Gson,所以要先引入依赖 打开build.gradle文件,代码如下:

implementation 'com.google.code.gson:gson:2.8.5'


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #android发送请求 #请求String #urlquo