How to send POST request in JSON using HTTPClient in Android?

后端 未结 5 1726
别跟我提以往
别跟我提以往 2020-11-22 07:49

I\'m trying to figure out how to POST JSON from Android by using HTTPClient. I\'ve been trying to figure this out for a while, I have found plenty of examples online, but I

5条回答
  •  梦谈多话
    2020-11-22 08:28

    I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.

    HttpURLConnection httpcon;  
    String url = null;
    String data = null;
    String result = null;
    try {
      //Connect
      httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
      httpcon.setDoOutput(true);
      httpcon.setRequestProperty("Content-Type", "application/json");
      httpcon.setRequestProperty("Accept", "application/json");
      httpcon.setRequestMethod("POST");
      httpcon.connect();
    
      //Write       
      OutputStream os = httpcon.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(data);
      writer.close();
      os.close();
    
      //Read        
      BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
    
      String line = null; 
      StringBuilder sb = new StringBuilder();         
    
      while ((line = br.readLine()) != null) {  
        sb.append(line); 
      }         
    
      br.close();  
      result = sb.toString();
    
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
    

提交回复
热议问题