Java Httpclient已弃用
我正在开发一个应用程序,使用Java Httpclient已弃用,java,php,android,eclipse,urlconnection,Java,Php,Android,Eclipse,Urlconnection,我正在开发一个应用程序,使用HTTPclient进行数据传输。由于不推荐使用HTTPClient,我想将网络部分移植到URLConnection ConectionHttpClient.java package conexao; import java.util.ArrayList; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.n
HTTPclient
进行数据传输。由于不推荐使用HTTPClient
,我想将网络部分移植到URLConnection
ConectionHttpClient.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();
}
}
}
}
}
包装conexao;
导入java.util.ArrayList;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.net.URI;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.conn.params.ConnManagerParams;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
公共类ConexaoHttpClient{
公共静态最终int HTTP_超时=30*1000;
私有静态HttpClient-HttpClient;
私有静态HttpClient getHttpClient(){
if(httpClient==null){
httpClient=新的DefaultHttpClient();
最终HttpParams HttpParams=httpClient.getParams();
setConnectionTimeout(httpParams,HTTP_超时);
HttpConnectionParams.setSoTimeout(httpParams,HTTP_超时);
setTimeout(httpParams,HTTP_TIMEOUT);
}返回httpClient;
}
公共静态字符串executaHttpPost(字符串url,ArrayList参数Post)引发异常{
BufferedReader BufferedReader=null;
试一试{
HttpClient=getHttpClient();
HttpPost HttpPost=新的HttpPost();
UrlEncodedFormEntity formEntity=新的UrlEncodedFormEntity(ParametersPost);
httpPost.setEntity(formEntity);
HttpResponse HttpResponse=client.execute(httpPost);
bufferedReader=新的bufferedReader(新的InputStreamReader(httpPost.getEntity().getContent());
StringBuffer StringBuffer=新的StringBuffer(“”);
字符串行=”;
字符串LS=System.getProperty(“line.separator”);
而((line=bufferedReader.readLine())!=null){
stringBuffer.append(行+LS);
}bufferedReader.close();
String resultado=stringBuffer.toString();
返回resultado;
}最后{
if(bufferedReader!=null){
试一试{
bufferedReader.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
}
MainActivity.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();
}
});
}
}
package.com.app.arts;
导入java.util.ArrayList;
导入org.apache.http.NameValuePair;
导入org.apache.http.message.BasicNameValuePair;
导入conexao.ConexaoHttpClient;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
public cla`在此处输入代码`ss MainActivity扩展活动{
EditText editEmail,editSenha;
按钮BTENTRAR、btnEsqueciSenha、btnCadastrar;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editEmail=(EditText)findViewById(R.id.editEmail);
editSenha=(EditText)findViewById(R.id.editSenha);
btentrar=(按钮)findviewbyd(R.id.btentrar);
btnEsqueciSenha=(按钮)findViewById(R.id.btnEsqueciSenha);
btnCadastrar=(按钮)findViewById(R.id.btnCadastrar);
btentrar.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
字符串urlPost=”http://192.168.25.5/arts/admin/login.php";
ArrayList参数Post=新建ArrayList();
参数post.add(新的BasicNameValuePair(“email”,editEmail.getText().toString());
parametrosPost.add(新的BasicNameValuePair(“senha”,editSenha.getText().toString());
字符串respostatoronada=null;
试一试{
respostatoronada=ConexaoHttpClient.executathttppost(urlPost,parametrosPost);
字符串resposta=respostatoronada.toString();
resposta=resposta.replaceAll(“//s+”,“”);
如果(响应等于(“1”))
mensagemExibir(“登录”、“Usuario Valido”);
其他的
mensagemExibir(“登录”、“通常无效”);
}捕获(异常错误){
Toast.makeText(MainActivity.this,“Erro:+Erro,Toast.LENGTH\u LONG);
}
}
公共void mensagexibir(字符串titulo,字符串texto){
AlertDialog.Builder mensage=新建AlertDialog.Builder(MainActivity.this);
mensagem.setTitle(提图洛);
mensagem.setMessage(texto);
mensage.setNeutralButton(“确定”,空);
mensagem.show();
}
});
}
}
我在Android中使用HttpURLConnection来做这类事情。
我使用下面的函数读取网页的内容。
我希望这能帮助你
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();
}
HttpClient
自API级别22以来已弃用
使用HttpURLConnection
有关
HttpClient
已弃用的详细信息,请参阅此为什么不使用改型或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");
公共接口服务{
@获取(“/users/{user}/repos”)
列出listRepos(@Path(“user”)字符串user);
}
RestAdapter RestAdapter=new RestAdapter.Builder()
.setEndpoint(“https://api.github.com")
.build();
GitHubService=restAdapter.create(GitHubService.class);
列表回购=service.listRepos(“octocat”);
更多信息:这是我应用于此版本android 22中httpclient不推荐使用的问题的解决方案 梅托德
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;
}
}
梅托多邮政
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;
}
}
publicstaticfinalstringuser\u-AGENT=“Mozilla/5.0”;
公共静态字符串sendPost(字符串_url,映射参数){
StringBuilder参数=新StringBuilder(“”);
字符串结果=”;
试一试{
对于(字符串s:parameter.keySet()){
参数追加(&“+s+”=”);