HttpUrlConnection与post请求和参数作为JSON对象?

时间:2018-01-03 09:16:22

标签: java android json

同样的问题here,但我想提出以下结构的请求。

"method": "post",

"url": parserApiUrl,

"data": {

"url": s3BaseUrl + imageKey

},

"headers": {

"x-api-key": "sdsdasdwdw"

}

1 个答案:

答案 0 :(得分:3)

我通过这个步骤找到了解决方案

urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("x-api-key", x_api);
                urlConnection.setRequestProperty("Accept", "application/json");

                String datajson =  "{\"file\": \""+imageString.trim()+"\"}";
                Log.e("data","json:"+datajson);

                OutputStream os = urlConnection.getOutputStream();
                os.write(datajson.getBytes("UTF-8"));
                os.close();