OkHttp 如何提交 POST 请求?
2020-03-25
关键字:
废话少说,上代码:
String travelIdJson = String.format(Locale.US, "{\"travelId\":[%d]}", track.getId()); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), travelIdJson); Request request = new Request.Builder() .url(ServerInfoManager.URL) .post(body) .addHeader("Authorization", DataManager.getUserManager().getToken()) .build(); Call call = new OkHttpClient().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } });
另一个兼容性更好的代码:
import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; OkHttpClient client = new OkHttpClient(); FormBody body = new FormBody.Builder() .add("Sn", "123456") .build(); Request request = new Request.Builder() .url(address) .post(body) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onResponse(Call arg0, Response arg1) throws IOException { Log.v(TAG, "onResponse()"); } @Override public void onFailure(Call arg0, IOException arg1) { Log.v(TAG, "onFailure()"); } });
+++