简体   繁体   中英

How do I change this code to make use of HttpURLConnection instead of httpClient

I know the HttpClient is depreceted and their alot of questions about an alternative. I have seen those questions and even read the documentation for HttpURLConnection. For the love of I cannot seem to get my code working with HttpUrlConnection. Are there any suggestions. Here is the code.

    @Override
        protected Void doInBackground(Void... params) {
            ContentValues dataToSend =new ContentValues();
            dataToSend.put("name", user.name);
            dataToSend.put("uersname", user.username);
            dataToSend.put("password", user.password);
            dataToSend.put("age", user.age + "");

      //  URL myUrl = new URL("http://192.168.182.15/connection.php");
     //   HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();

        HttpParams httpRequestParams = getHttpRequestParams();

        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDRESS
                + "Register.php");

        try {
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            client.execute(post);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private HttpParams getHttpRequestParams() {
        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams,
                CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams,
                CONNECTION_TIMEOUT);
        return httpRequestParams;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        progressDialog.dismiss();
        userCallBack.done(null);
    }

Use this JSONParser class this is easy to use.

JSONParser.java

public class JSONParser {

    public JSONParser() {

    }

    public String makeBufferCall(String serviceUrl) {
        Boolean registered = false;
        StringBuffer response = new StringBuffer();
        URL url = null;

        HttpURLConnection conn = null;
        try {

            url = new URL(serviceUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setDoOutput(false);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            }
            registered = true;

            // Get Response
            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;

            while ((line = rd.readLine()) != null) {
                response.append(line);

            }
            rd.close();

        } catch (Exception e) {
            e.printStackTrace();
            //ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
            //response.append("Error");
        }
        Log.v("Response:", response.toString());
        return response.toString();

    }


}

And use this class in AsyncTask using just calling the method. So don't need to whole code write in every time.

 @Override
        protected Void doInBackground(Void... params) {
            // Locate the Offer_POJO Class
            property_data = new ArrayList<Contract_POJO>();
            // Create an array to populate the spinner
            property = new ArrayList<String>();

            JSONParser call = new JSONParser();
            jsonstr = call.makeBufferCall(url_property);
            Log.d("Response: ", "> " + jsonstr);

            return null;
        }

I am not run this code but I think it will work fine..

@Override
    protected Void doInBackground(Void... params) {

        ContentValues dataToSend =new ContentValues();
        dataToSend.put("name", user.name);
        dataToSend.put("uersname", user.username);
        dataToSend.put("password", user.password);
        dataToSend.put("age", user.age + "");

        //  URL myUrl = new URL("http://192.168.182.15/connection.php");
        //   HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();

        try {
            URL myUrl = new URL("http://192.168.182.15/connection.php");
            HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();

            HttpClient client = new HttpClient();
            HttpMethod post = new PostMethod("SERVER_ADDRESS"+ "Register.php");

            post.setQueryString(new UrlEncodedFormEntity(dataToSend));

            client.executeMethod(post);

        } catch (Exception e) {
            e.printStackTrace();
        }



        return null;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM