如何更改此代码以使用HttpURLConnection而不是httpClient

时间:2016-03-08 03:18:48

标签: java android

我知道HttpClient已被删除,并且他们对替代品有很多疑问。我已经看过这些问题,甚至阅读了HttpURLConnection的文档。为了爱我,似乎无法让我的代码使用HttpUrlConnection。有什么建议吗?这是代码。

    @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);
    }

2 个答案:

答案 0 :(得分:0)

使用这个易于使用的JSONParser类。

<强> 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();

    }


}

只需调用方法即可在AsyncTask中使用此类。因此,不需要每次都编写完整的代码。

 @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;
        }

答案 1 :(得分:0)

我没有运行此代码,但我认为它会正常运行..

@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;
    }