データ転送に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();
}
}
}
}
}
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();
}
});
}
}
これは、httpclientがこのバージョンのAndroid 22で非推奨になった問題に適用したソリューションです。
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;
}
}
メトドポスト
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;
}
}
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");
私はHttpURLConnectionを使用して、Androidでこの種の処理を実行します。以下の関数を使用して、Webページのコンテンツを読み取りました。これがお役に立てば幸いです。
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
非推奨に関連する詳細については、これを参照してください http://Android-developers.blogspot.in/2011/09/androids-http-clients.html
Google独自のバージョンのApacheコンポーネントのみが非推奨になりました。ここで説明したように、問題なく引き続き使用できます: https://stackoverflow.com/a/37623038/1727132