1,首先添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
implementation 'com.google.code.gson:gson:2.8.6'
2,上传一个简单的字符串到服务器
String name = editText.getText.toString();
RequestBody requestBody = new FormBody.Builder()
.add("vendovID", name)
.build();
final OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("http://192.168.123.195:5000/you/api")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(res);
}
});
}
});
3,上传一个json到服务器
首先定义一个实体类,get set方法
然后按照下面的方法
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String name = editText.getText().toString();
final Entity entity = new Entity();
entity.setVendovID(MainActivity.this.name);
Gson gson = new Gson();
final String json = gson.toJson(entity);
RequestBody requestBody = RequestBody.create(
json, JSON);
final OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("http://192.168.123.195:5000/you/api")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(res);
}
});
}
});
4,最后别忘了在Manifest添加权限,点击按钮发送后台可以接收到你当前发送的数据
菜鸟入门,写的不好希望各位大哥多多指教,共同进步