web-dev-qa-db-ja.com

パッケージorg.Apache.http.clientは存在しません

ログイン資格情報をチェックしようとしていますが、これらのエラーが何度も発生します。すべてを試しました。私はAndroidに新しいものがあります。どんな種類のヘルプも高く評価されます。同じものを実装する他の良い方法があれば、暗示する方法を知りたいです。

エラー

Error:(19, 30) error: package org.Apache.http.client does not exist
Error:(15, 23) error: package org.Apache.http does not exist
Error:(16, 23) error: package org.Apache.http does not exist
Error:(17, 23) error: package org.Apache.http does not exist
Error:(18, 30) error: package org.Apache.http.client does not exist
Error:(20, 37) error: package org.Apache.http.client.entity does not exist
Error:(21, 38) error: package org.Apache.http.client.methods does not exist
Error:(22, 35) error: package org.Apache.http.impl.client does not exist
Error:(23, 31) error: package org.Apache.http.message does not exist
Error:(79, 22) error: cannot find symbol class NameValuePair
Error:(85, 49) error: cannot find symbol class DefaultHttpClient
Error:(86, 21) error: cannot find symbol class HttpPost
Error:(86, 45) error: cannot find symbol class HttpPost
Error:(88, 44) error: cannot find symbol class UrlEncodedFormEntity
Error:(90, 21) error: cannot find symbol class HttpResponse
Error:(92, 21) error: cannot find symbol class HttpEntity
Error:(105, 26) error: cannot find symbol class ClientProtocolException
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Error:(85, 21) error: cannot find symbol class HttpClient
Error:(81, 40) error: cannot find symbol class BasicNameValuePair
Error:(80, 40) error: cannot find symbol class BasicNameValuePair
Error:(79, 68) error: cannot find symbol class NameValuePair    

MainActivity.Java

package com.tarun.proxy_maar;

import Android.app.Dialog;
import Android.app.ProgressDialog;
import Android.content.Intent;
import Android.os.AsyncTask;
import Android.os.Bundle;
import Android.support.v7.app.AppCompatActivity;
import Android.view.Menu;
import Android.view.MenuItem;
import Android.view.View;
import Android.widget.EditText;
import Android.widget.Toast;

import org.Apache.http.HttpEntity;
import org.Apache.http.HttpResponse;
import org.Apache.http.NameValuePair;
import org.Apache.http.client.ClientProtocolException;
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.DefaultHttpClient;
import org.Apache.http.message.BasicNameValuePair;

import Java.io.BufferedReader;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.io.UnsupportedEncodingException;
import Java.util.ArrayList;
import Java.util.List;


public class MainActivity extends AppCompatActivity {

    private EditText editTextUserName;
    private EditText editTextPassword;

    public static final String USER_NAME = "USERNAME";

    String username;
    String password;

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

        editTextUserName = (EditText) findViewById(R.id.editTextUserName);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    }

    public void invokeLogin(View view){
        username = editTextUserName.getText().toString();
        password = editTextPassword.getText().toString();

        login(username,password);

    }

    private void login(final String username, String password) {

        class LoginAsync extends AsyncTask<String, Void, String>{

            private Dialog loadingDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
            }

            @Override
            protected String doInBackground(String... params) {
                String uname = params[0];
                String pass = params[1];

                InputStream is = null;
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("username", uname));
                nameValuePairs.add(new BasicNameValuePair("password", pass));
                String result = null;

                try{
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://shaadi.web44.net/hello.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();

                    is = entity.getContent();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                String s = result.trim();
                loadingDialog.dismiss();
                if(s.equalsIgnoreCase("success")){
                    Intent intent = new Intent(MainActivity.this, UserProfile.class);
                    intent.putExtra(USER_NAME, username);
                    finish();
                    startActivity(intent);
                }else {
                    Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
                }
            }
        }

        LoginAsync la = new LoginAsync();
        la.execute(username, password);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
12
tarun14110

Build.gradleに追加します:

Android {
    useLibrary 'org.Apache.http.legacy'
}

または、HttpURLConnection class代わりに。

46
Patricia

DefaultHttpClientおよびNameValuePairクラスは、APIレベル22で廃止され、APIレベル23で削除されました。

Googleはそれらのドキュメントも削除しました。

ドキュメントがまだ完成していない場合、このような基本的なタスクのためにHttpUrlConnectionに切り替えることをお勧めします。

APIレベル23で動作するAsyncTaskの修正バージョンは次のとおりです。

  class LoginAsync extends AsyncTask<String, Void, String>{

        private Dialog loadingDialog;
        String url = "http://shaadi.web44.net/hello.php";

        String charset = "UTF-8";
        HttpURLConnection conn;
        DataOutputStream wr;
        StringBuilder result = new StringBuilder();
        URL urlObj;
        JSONObject jObj = null;
        StringBuilder sbParams;
        String paramsString;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
        }

        @Override
        protected String doInBackground(String... params) {
            String uname = params[0];
            String pass = params[1];

            sbParams = new StringBuilder();

            try {
                sbParams.append("name").append("=")
                        .append(URLEncoder.encode(uname, charset));
                sbParams.append("&");
                sbParams.append("password").append("=")
                        .append(URLEncoder.encode(pass, charset));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                //response from the server
                InputStream in = new BufferedInputStream(conn.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

            conn.disconnect();

            return result.toString();
        }

        @Override
        protected void onPostExecute(String result){
            String s = result.trim();
            loadingDialog.dismiss();
            if(s.equalsIgnoreCase("success")){
                Intent intent = new Intent(MainActivity.this, UserProfile.class);
                intent.putExtra(USER_NAME, username);
                finish();
                startActivity(intent);
            }else {
                Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
            }
        }
    }

完全なクラスコード:

import Android.app.Dialog;
import Android.app.ProgressDialog;
import Android.content.Intent;
import Android.os.AsyncTask;
import Android.os.Bundle;
import Android.support.v7.app.AppCompatActivity;
import Android.view.Menu;
import Android.view.MenuItem;
import Android.view.View;
import Android.widget.EditText;
import Android.widget.Toast;
import org.json.JSONObject;
import Java.io.BufferedInputStream;
import Java.io.BufferedReader;
import Java.io.DataOutputStream;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.io.UnsupportedEncodingException;
import Java.net.HttpURLConnection;
import Java.net.URL;
import Java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

    private EditText editTextUserName;
    private EditText editTextPassword;

    public static final String USER_NAME = "USERNAME";

    String username;
    String password;

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

        editTextUserName = (EditText) findViewById(R.id.editTextUserName);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    }

    public void invokeLogin(View view){
        username = editTextUserName.getText().toString();
        password = editTextPassword.getText().toString();

        login(username,password);

    }

    private void login(final String username, String password) {

        class LoginAsync extends AsyncTask<String, Void, String>{

            private Dialog loadingDialog;
            String url = "http://shaadi.web44.net/hello.php";

            String charset = "UTF-8";
            HttpURLConnection conn;
            DataOutputStream wr;
            StringBuilder result = new StringBuilder();
            URL urlObj;
            JSONObject jObj = null;
            StringBuilder sbParams;
            String paramsString;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
            }

            @Override
            protected String doInBackground(String... params) {
                String uname = params[0];
                String pass = params[1];

                sbParams = new StringBuilder();

                try {
                    sbParams.append("name").append("=")
                            .append(URLEncoder.encode(uname, charset));
                    sbParams.append("&");
                    sbParams.append("password").append("=")
                            .append(URLEncoder.encode(pass, charset));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                try {
                    urlObj = new URL(url);

                    conn = (HttpURLConnection) urlObj.openConnection();

                    conn.setDoOutput(true);

                    conn.setRequestMethod("POST");

                    conn.setRequestProperty("Accept-Charset", charset);

                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(15000);

                    conn.connect();

                    paramsString = sbParams.toString();

                    wr = new DataOutputStream(conn.getOutputStream());
                    wr.writeBytes(paramsString);
                    wr.flush();
                    wr.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    //response from the server
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }

                conn.disconnect();

                return result.toString();
            }

            @Override
            protected void onPostExecute(String result){
                String s = result.trim();
                loadingDialog.dismiss();
                if(s.equalsIgnoreCase("success")){
                    Intent intent = new Intent(MainActivity.this, UserProfile.class);
                    intent.putExtra(USER_NAME, username);
                    finish();
                    startActivity(intent);
                }else {
                    Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
                }
            }
        }

        LoginAsync la = new LoginAsync();
        la.execute(username, password);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
7
Daniel Nugent