如何将HttpsURLConnection的GET请求修改为带参数的POST请求
完整修改方案
1. 调整参数拼接逻辑
POST请求的JSON参数不需要拼接在URL后面,直接使用基础接口地址即可,删掉原有JSON URL编码、参数拼URL的冗余逻辑,修改后代码如下:
String RequestString = ((myrequest) request).getJson(); // 直接使用基础接口地址,不需要拼接编码后的参数 mURL = defautlUrl; Log.e( TAG, "Request URL: " + mURL );
2. 调整HttpsURLConnection配置并写入请求体
除了你已知的请求头、请求方法修改外,需要额外开启输出流权限,再把原始JSON字符串写入请求体即可,完整代码如下:
try { HttpsURLConnection mUrlConnection = (HttpsURLConnection) new URL( mURL ).openConnection(); // 你已知的修改内容 mUrlConnection.setRequestProperty("Content-Type", "application/json; utf-8"); mUrlConnection.setRequestMethod( "POST" ); mUrlConnection.setConnectTimeout( 12000 ); mUrlConnection.setReadTimeout( 30000 ); // 新增:开启输出权限,允许向服务端写入请求体 mUrlConnection.setDoOutput(true); // 新增:写入JSON请求体(API 19及以上支持try-with-resources自动关流) try (OutputStream os = mUrlConnection.getOutputStream()) { byte[] jsonBytes = RequestString.getBytes("utf-8"); os.write(jsonBytes, 0, jsonBytes.length); } mUrlConnection.connect(); // 后续可通过getResponseCode()、getInputStream()获取接口响应结果 }
如果你的项目minSdkVersion低于19,不支持try-with-resources语法,手动关流即可:
OutputStream os = null; try { os = mUrlConnection.getOutputStream(); byte[] jsonBytes = RequestString.getBytes("utf-8"); os.write(jsonBytes, 0, jsonBytes.length); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } }
注意事项
- 不需要对JSON字符串做
URLEncoder.encode编码:Content-Type: application/json格式要求请求体直接传输原始JSON内容,URL编码后的内容会导致服务端解析失败 - 写完请求体后再调用
connect()或者获取响应的相关方法,顺序不能乱 - 如果接口响应异常,可以先抓包确认请求体格式、编码是否符合服务端要求
内容的提问来源于stack exchange,提问作者Carlos Melendez
相关产品推荐
相关产品推荐

