在Android应用中向ASP.NET Web API发送POST请求是一种常见的跨平台通信方式,涉及客户端(Android)与服务器端(ASP.NET)之间的HTTP交互。POST请求通常用于向服务器提交数据,如用户登录信息、表单数据等。
public class HttpPostRequest {
public static String sendPost(String urlStr, String jsonInputString) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
// 发送请求数据
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// 获取响应
try(BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
}
}
}
首先在build.gradle中添加依赖:
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
然后实现POST请求:
public class OkHttpPostRequest {
private final OkHttpClient client = new OkHttpClient();
public String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, MediaType.get("application/json"));
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return response.body().string();
}
}
}
首先在build.gradle中添加依赖:
implementation 'com.android.volley:volley:1.2.1'
然后实现POST请求:
public class VolleyPostRequest {
public void postRequest(Context context, String url, String requestBody) {
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
response -> {
// 处理成功响应
Log.d("Response", response);
},
error -> {
// 处理错误
Log.e("Error", error.toString());
}) {
@Override
public byte[] getBody() {
return requestBody.getBytes(StandardCharsets.UTF_8);
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(stringRequest);
}
}
[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
[HttpPost]
public IActionResult Post([FromBody] UserModel user)
{
if (user == null)
{
return BadRequest();
}
// 处理接收到的数据
return Ok(new { Message = "Data received", User = user });
}
}
public class UserModel
{
public string Username { get; set; }
public string Password { get; set; }
}
原因:网络不稳定或服务器响应慢 解决:
client.newBuilder().connectTimeout(10, TimeUnit.SECONDS).build()
原因:请求格式不正确或缺少必要参数 解决:
原因:Content-Type与服务器期望的不匹配 解决:
connection.setRequestProperty("Content-Type", "application/json")
原因:浏览器安全策略阻止跨域请求 解决:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllowAll");
// 其他中间件...
}
原因:服务器使用自签名证书或证书不受信任 解决:
没有搜到相关的文章