Sending json object via http post method in android

前端 未结 2 1877
粉色の甜心
粉色の甜心 2020-12-18 16:19

its NOT DUPLICATE.Link that has been provided is an OLD one.\"http client\" has been removed in api23

I want to send json object:

<
2条回答
  •  死守一世寂寞
    2020-12-18 16:34

    Define a class AsyncT and call it in onCreate method using:

    AsyncT asyncT = new AsyncT();
    asyncT.execute();
    

    Class definition:

    class AsyncT extends AsyncTask{
    
            @Override
            protected Void doInBackground(Void... params) {
    
                try {
                    URL url = new URL(""); //Enter URL here
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
                    httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
                    httpURLConnection.connect();
    
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("para_1", "arg_1");
    
                    DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                    wr.writeBytes(jsonObject.toString());
                    wr.flush();
                    wr.close();
    
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
                return null;
            }
    
    
        }
    

提交回复
热议问题