httpsparams,basicHttpParams,httpconnectionparams,defaulthttpclient已弃用

时间:2017-07-28 11:17:21

标签: java android http

我开发防盗应用程序并找到了这个连接类,但有一些不赞成的东西:

这里的DEPESated行:  httppparams,basicHttpParams,httpconnectionparams,defaulthttpclient 我怎么解决? 这是不推荐的行的屏幕截图:

screenshot

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

public class HttpRmi {

private HttpPost request = null;
private List<NameValuePair> nameValuePairs = null;
private int connectionTimeoutMillis = 300*1000;
private int socketTimeoutMillis = 0;
private HttpClient httpClient;

public HttpRmi(String url){
    request = new HttpPost(url);
    nameValuePairs = new ArrayList<NameValuePair>(1);
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,       connectionTimeoutMillis);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
    HttpProtocolParams.setContentCharset(httpParams, "utf-8");

    httpClient = new DefaultHttpClient(httpParams);
}

public HttpRmi add(String key, String value){
    nameValuePairs.add(new BasicNameValuePair(key, value));
    return this;
}

public String execute() throws IOException{
    String response = "";
    try{
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8" )    );

        response = httpClient.execute(request, new BasicResponseHandler());
    }catch(Exception e){
        e.printStackTrace();
        throw new IOException("no connection");
    }

    return response;
}

}

2 个答案:

答案 0 :(得分:0)

Httpclient的最佳替代方法是使用OKHttpHttpUrlConnection

  

新应用程序应该使用HttpURLConnection;这是我们将成为的地方   把我们的精力用在前面。 link

答案 1 :(得分:0)

使用HttpURLConnection

        import java.net.HttpURLConnection;
        import java.net.URL;


        String retFromServer = "";
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL("http://www.somedomain.com/);
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();
            InputStreamReader inRead = new InputStreamReader(in);

            retFromServer = IOUtils.toString(inRead);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }