How to stream a JSON object to a HttpURLConnection POST request

前端 未结 5 2034
鱼传尺愫
鱼传尺愫 2021-02-05 14:09

I can not see what is wrong with this code:

JSONObject msg;  //passed in as a parameter to this method

HttpURLConnection httpCon = (HttpURLConnection) url.openC         


        
5条回答
  •  情歌与酒
    2021-02-05 14:56

    this without json String post data to server

     class PostLogin extends AsyncTask {
            @Override
            protected String doInBackground(Void... params) {
                String response = null;
    
                Uri.Builder builder= new Uri.Builder().appendQueryParameter("username","amit").appendQueryParameter("password", "amit");
                String parm=builder.build().getEncodedQuery();
          try
               {
    
                   response = postData("your url here/",parm);
               }catch (Exception e)
               {
                   e.printStackTrace();
               }
                Log.d("test", "response string is:" + response);
                return response;
            }
        }
    
    
    private String postData(String path, String param)throws IOException {
            StringBuffer response = null;
    
            URL  url = new URL(path);
            HttpURLConnection  connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
    //        connection.setRequestProperty("Content-Type", "application/json");
    //        connection.setRequestProperty("Accept", "application/json");
                OutputStream out = connection.getOutputStream();
                out.write(param.getBytes());
                out.flush();
                out.close();
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    response = new StringBuffer();
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                    br.close();
                }
    
            return response.toString();
        }
    

提交回复
热议问题