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

Java 如何更改此代码以使用HttpURLConnection而不是httpClient,java,android,Java,Android,我知道HttpClient已经不受欢迎了,他们对替代方案有很多疑问。我已经看到了这些问题,甚至阅读了HttpURLConnection的文档。看在上帝的份上,我似乎无法让我的代码与HttpUrlConnection一起工作。有什么建议吗。这是代码 @Override protected Void doInBackground(Void... params) { ContentValues dataToSend =new ContentValues(

我知道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);
    }

使用这个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;
        }
@覆盖
受保护的Void doInBackground(Void…参数){
//找到Offer_POJO类
属性_data=new ArrayList();
//创建一个数组以填充微调器
属性=新的ArrayList();
JSONParser调用=新建JSONParser();
jsonstr=call.makeBufferCall(url_属性);
Log.d(“响应:”、“>”+jsonstr);
返回null;
}

我没有运行此代码,但我认为它可以正常工作。

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

这真的不是你问题的答案,所以我将把它作为一个评论发布。我的建议是,不要用那个!使用改装+rxandroid。最好是习惯适当的图书馆。检查一下这是关于JSONParser.java的吗?看看像Volley或Reformation这样的网络库,它会比它简单得多。此外,HttpClient和HttpUrlConnection将不再更新。所以我的建议是不要使用它们。你可以使用这段代码。我已经回答了这里的问题,我建议你使用第三方库..像volley,retro…它可以节省代码行数和时间,性能也很好。这段代码与注册php文件一起工作。所以JSON不是我想要的。我希望在使用HttpURLConnection时尽可能保持我发布的代码的完整性。