can use httpClient in Android Studio?

前端 未结 2 1405
情深已故
情深已故 2020-12-11 13:56

i use httpClient to send data to php file like this

php

 

and i add

相关标签:
2条回答
  • 2020-12-11 13:59

    Http client is deprecated in api level 22. So you must use open OpenUrlConnection. You can use this code

    public class FetchUrl {
    
        private URL url;
    
        public String fetchUrl(String urlString, HashMap<String, String> values) {
            String response = "";
            try {
                url = new URL(urlString);
                Log.d("url string", urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
    
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                        os, "UTF-8"));
                writer.write(getPostDataString(values));
    
                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();
    
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                } else {
                    response = "";
    
                    throw new Exception(responseCode + "");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return response;
        }
    
        private String getPostDataString(HashMap<String, String> params)
                throws UnsupportedEncodingException {
            StringBuilder result = new StringBuilder();
            boolean first = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (first)
                    first = false;
                else
                    result.append("&");
    
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            Log.d("query string", result.toString());
            return result.toString();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-11 14:06

    try below code

          HttpEntity httpEntity = httpResponse.getEntity();
      if (resEntity != null) {
    
      String response_From_Server = EntityUtils.toString(resEntity);
      Log.e("","response from server is : "+response_From_Server);
     }
    
    0 讨论(0)
提交回复
热议问题