eclipse 不推荐使用 Httpclient

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29812992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 22:34:46  来源:igfitidea点击:

Httpclient deprecated

javaphpandroideclipseurlconnection

提问by Fernando Castilho Marmol

I'm developing an app using HTTPclientfor datatransfer. Since HTTPClientis deprecated, I want to port the network part to URLConnection.

我正在开发HTTPclient用于数据传输的应用程序。由于HTTPClient已弃用,我想将网络部分移植到URLConnection.

ConectionHttpClient.java

连接HttpClient.java

package conexao;

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

public class ConexaoHttpClient {
    public static final int HTTP_TIMEOUT = 30 * 1000;
    private static HttpClient httpClient;
    private static HttpClient getHttpClient(){
        if (httpClient == null){
            httpClient = new DefaultHttpClient();
            final HttpParams httpParams = httpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(httpParams, HTTP_TIMEOUT);
        }return httpClient;

    }

public static String executaHttpPost(String url, ArrayList<NameValuePair> parametrosPost) throws Exception{
    BufferedReader bufferedReader = null;
    try{
        HttpClient client = getHttpClient();
        HttpPost httpPost = new HttpPost();
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parametrosPost);
        httpPost.setEntity(formEntity);
        HttpResponse httpResponse = client.execute(httpPost);
        bufferedReader = new BufferedReader(new InputStreamReader(httpPost.getEntity().getContent()));
        StringBuffer stringBuffer = new StringBuffer(" ");
        String line = " ";
        String LS = System.getProperty("line.separator");
        while ((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line + LS); 
        }bufferedReader.close();


    String resultado = stringBuffer.toString();
    return resultado;
}finally{
    if (bufferedReader != null){
        try{
            bufferedReader.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

}
}

MainActivity.java

主活动.java

package com.app.arts;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import conexao.ConexaoHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public cla`enter code here`ss MainActivity extends Activity {

    EditText editEmail, editSenha;
    Button btnEntrar, btnEsqueciSenha, btnCadastrar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    editEmail = (EditText)findViewById(R.id.editEmail);
    editSenha = (EditText)findViewById(R.id.editSenha);
    btnEntrar = (Button)findViewById(R.id.btnEntrar);
    btnEsqueciSenha = (Button)findViewById(R.id.btnEsqueciSenha);
    btnCadastrar = (Button)findViewById(R.id.btnCadastrar);

    btnEntrar.setOnClickListener(new View.OnClickListener() {


        public void onClick(View v){

        String urlPost="http://192.168.25.5/arts/admin/login.php";
        ArrayList<NameValuePair> parametrosPost = new ArrayList<NameValuePair>();
        parametrosPost.add(new BasicNameValuePair("email", editEmail.getText().toString()));
        parametrosPost.add(new BasicNameValuePair("senha", editSenha.getText().toString()));
        String respostaRetornada = null;
        try{
         respostaRetornada = ConexaoHttpClient.executaHttpPost(urlPost, parametrosPost);
         String resposta = respostaRetornada.toString();
         resposta = resposta.replaceAll("//s+", "");
         if (resposta.equals("1"))
           mensagemExibir("Login", "Usuario Valido");
         else
           mensagemExibir("Login", "Usuario Invalido");  
        }catch(Exception erro){
          Toast.makeText(MainActivity.this, "Erro: " +erro, Toast.LENGTH_LONG);
         }  
       }    
         public void mensagemExibir(String titulo, String texto){
      AlertDialog.Builder mensagem = new AlertDialog.Builder(MainActivity.this);
      mensagem.setTitle(titulo);
      mensagem.setMessage(texto);
      mensagem.setNeutralButton("OK", null);
      mensagem.show();


     }


    });
}
}

回答by Frutos Marquez

This is the solution that I have applied to the problem that httpclient deprecated in this version of android 22

这是我已应用于此版本的android 22中不推荐使用httpclient的问题的解决方案

Metod Get

获取方法

 public static String getContenxtWeb(String urlS) {
    String pagina = "", devuelve = "";
    URL url;
    try {
        url = new URL(urlS);
        HttpURLConnection conexion = (HttpURLConnection) url
                .openConnection();
        conexion.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conexion.getInputStream()));
            String linea = reader.readLine();
            while (linea != null) {
                pagina += linea;
                linea = reader.readLine();
            }
            reader.close();

            devuelve = pagina;
        } else {
            conexion.disconnect();
            return null;
        }
        conexion.disconnect();
        return devuelve;
    } catch (Exception ex) {
        return devuelve;
    }
}

Metodo Post

梅多多邮报

 public static final String USER_AGENT = "Mozilla/5.0";



public static String sendPost(String _url,Map<String,String> parameter)  {
    StringBuilder params=new StringBuilder("");
    String result="";
    try {
    for(String s:parameter.keySet()){
        params.append("&"+s+"=");

            params.append(URLEncoder.encode(parameter.get(s),"UTF-8"));
    }


    String url =_url;
    URL obj = new URL(_url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "UTF-8");

    con.setDoOutput(true);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
    outputStreamWriter.write(params.toString());
    outputStreamWriter.flush();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + params);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine + "\n");
    }
    in.close();

        result = response.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
    return  result;
    }

}

回答by Christian Abella

I use HttpURLConnection to do this kind of stuff in Android. I used the function below to read a content of a web page. I hope this can help you.

我使用 HttpURLConnection 在 Android 中做这种事情。我使用下面的函数来读取网页的内容。我希望这可以帮助你。

public String GetWebPage(String sAddress) throws IOException
{
    StringBuilder sb = new StringBuilder();

    BufferedInputStream bis = null;
    URL url = new URL(sAddress);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int responseCode;

    con.setConnectTimeout( 10000 );
    con.setReadTimeout( 10000 );

    responseCode = con.getResponseCode();

    if ( responseCode == 200)
    {
      bis = new java.io.BufferedInputStream(con.getInputStream());
      BufferedReader reader = new BufferedReader(new InputStreamReader(bis, "UTF-8"));
      String line = null;

      while ((line = reader.readLine()) != null)
        sb.append(line);

      is.close();
    }

    return sb.toString();
}

回答by Billy Riantono

Why you dont use Retrofit or OkHttp ? It is much simpler

为什么不使用 Retrofit 或 OkHttp ?简单多了

 public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
  } 


 RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();

 GitHubService service = restAdapter.create(GitHubService.class);  

 List<Repo> repos = service.listRepos("octocat");

More Information : http://square.github.io/retrofit/

更多信息:http: //square.github.io/retrofit/

回答by Rakesh Kalashetti

HttpClientDeprecated since API level 22

HttpClient自 API 级别 22 起已弃用

Use HttpURLConnection

HttpURLConnection

for more information related to HttpClientDeprecated refer this http://android-developers.blogspot.in/2011/09/androids-http-clients.html

有关HttpClient已弃用的更多信息,请参阅此http://android-developers.blogspot.in/2011/09/androids-http-clients.html

回答by Jehy

Only google's own version of apache components is deprecated. You can still continue using it without any troubles like I described here: https://stackoverflow.com/a/37623038/1727132

只有 google 自己版本的 apache 组件被弃用。您仍然可以继续使用它而不会像我在这里描述的那样遇到任何麻烦:https: //stackoverflow.com/a/37623038/1727132