Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android Studio不推荐使用HttpParams、HttpConnectionParams、ConnManagerParams和setTimeout_Java_Android - Fatal编程技术网

Java Android Studio不推荐使用HttpParams、HttpConnectionParams、ConnManagerParams和setTimeout

Java Android Studio不推荐使用HttpParams、HttpConnectionParams、ConnManagerParams和setTimeout,java,android,Java,Android,你好,我是Android编程新手。我想制作一个可以将Android连接到web服务器的应用程序。以下是我使用的代码: public void cari (View v){ ArrayList<NameValuePair> arData = new ArrayList<NameValuePair>(); arData.add(new BasicNameValuePair("nama", edNama.getText().toString()

你好,我是Android编程新手。我想制作一个可以将Android连接到web服务器的应用程序。以下是我使用的代码:

public void cari (View v){

        ArrayList<NameValuePair> arData = new ArrayList<NameValuePair>();
        arData.add(new BasicNameValuePair("nama", edNama.getText().toString()));
        String respon = null;

        try {
            respon = KoneksiHTTP.eksekusiHttpPost("http://example.com/myphp.php", arData);
            String r = respon.toString();
            r = r.trim();

            AlertDialog close = new AlertDialog.Builder(this)
                    .setTitle("ESTIMASI MANFAAT")
                    .setMessage(r.toString())
                    .setNegativeButton("Kembali", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dlg, int sumthin) {
                            // TODO Auto-generated method stub
                        }
                    })
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            edNama.setText(null);
        }
}
但它没有效果。我应该用什么来代替

这是我的身材

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.example.plz.taspenmobile"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.google.android.gms:play-services-maps:8.4.0'
    compile 'com.google.android.gms:play-services-location:8.4.0'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}
显示respon的代码:

try {
            CallWebService respon = new CallWebService("POST", "http://example.com/myphp.php", apiParams) {
                @Override
                public void OnStartingService() {
                    super.OnStartingService();
                }

               //@Override
                public void OnGettingResult(JSONObject jsonObject) throws JSONException, MethodNotDefinedException {
                    super.OnGettingResult(toString());
                }
            };


            String r = respon.toString();
            r = r.trim();
            AlertDialog close = new AlertDialog.Builder(estimasi.this)
                    .setTitle("Estimasi Manfaat")
                    .setMessage(r.toString())
                    .setNegativeButton("Kembali", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dlg, int sumthin) {
                            // TODO Auto-generated method stub
                        }
                    })
                    .show();


        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            edNama.setText(null);
        }

您必须使用
HttpURLConnection

请参考以下两种方法

1。用于获取方法。

public static String getHttpResponse(String url) {

        StringBuffer responseString = null;
        String inputLine;
        HttpURLConnection connection = null;

        try {
            URL dataUrl = new URL(url);
            connection = (HttpURLConnection) dataUrl.openConnection();
            // optional default is GET
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            Log.w("Some error occured", e);
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
    public static String postHttpResponse(String dataUrl, HashMap<String, String> postData) {

        StringBuffer responseString = null;
        HttpURLConnection connection = null;
        String inputLine;

        try {
            URL postUrl = new URL(dataUrl);
            String email_id = postData.get("email_id");
            String device_id = postData.get("device_id");
            String status = postData.get("status");

            connection = (HttpURLConnection) postUrl.openConnection();

            String urlParameters = "device_id=" + device_id + "&email_id=" + email_id + "&status=" + status;
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
2。用于POST方法。

public static String getHttpResponse(String url) {

        StringBuffer responseString = null;
        String inputLine;
        HttpURLConnection connection = null;

        try {
            URL dataUrl = new URL(url);
            connection = (HttpURLConnection) dataUrl.openConnection();
            // optional default is GET
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            Log.w("Some error occured", e);
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
    public static String postHttpResponse(String dataUrl, HashMap<String, String> postData) {

        StringBuffer responseString = null;
        HttpURLConnection connection = null;
        String inputLine;

        try {
            URL postUrl = new URL(dataUrl);
            String email_id = postData.get("email_id");
            String device_id = postData.get("device_id");
            String status = postData.get("status");

            connection = (HttpURLConnection) postUrl.openConnection();

            String urlParameters = "device_id=" + device_id + "&email_id=" + email_id + "&status=" + status;
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
公共静态字符串postHttpResponse(字符串dataUrl、HashMap postData){
StringBuffer responseString=null;
HttpURLConnection=null;
字符串输入线;
试一试{
URL postrl=新URL(数据URL);
字符串email_id=postData.get(“email_id”);
字符串device_id=postData.get(“device_id”);
字符串状态=postData.get(“状态”);
connection=(HttpURLConnection)postrl.openConnection();
字符串urlParameters=“device_id=“+device_id+”&email_id=“+email_id+”&status=“+status;
connection.setRequestMethod(“POST”);
connection.setDoOutput(真);
DataOutputStream wr=新的DataOutputStream(connection.getOutputStream());
writeBytes(URL参数);
wr.flush();
wr.close();
int responseCode=connection.getResponseCode();
如果(响应代码==200){
BufferedReader in=新的BufferedReader(新的InputStreamReader(connection.getInputStream());
responseString=新的StringBuffer();
而((inputLine=in.readLine())!=null){
responseString.append(输入行);
}
in.close();
}
}捕获(例外e){
e、 printStackTrace();
返回null;
}最后{
试一试{
连接断开();
}捕获(例外e){
e、 printStackTrace();//如果您想了解有关失败的更多信息。。。
返回null;
}
}
返回responseString.toString();
}

您必须使用
HttpURLConnection

请参考以下两种方法

1。用于获取方法。

public static String getHttpResponse(String url) {

        StringBuffer responseString = null;
        String inputLine;
        HttpURLConnection connection = null;

        try {
            URL dataUrl = new URL(url);
            connection = (HttpURLConnection) dataUrl.openConnection();
            // optional default is GET
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            Log.w("Some error occured", e);
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
    public static String postHttpResponse(String dataUrl, HashMap<String, String> postData) {

        StringBuffer responseString = null;
        HttpURLConnection connection = null;
        String inputLine;

        try {
            URL postUrl = new URL(dataUrl);
            String email_id = postData.get("email_id");
            String device_id = postData.get("device_id");
            String status = postData.get("status");

            connection = (HttpURLConnection) postUrl.openConnection();

            String urlParameters = "device_id=" + device_id + "&email_id=" + email_id + "&status=" + status;
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
2。用于POST方法。

public static String getHttpResponse(String url) {

        StringBuffer responseString = null;
        String inputLine;
        HttpURLConnection connection = null;

        try {
            URL dataUrl = new URL(url);
            connection = (HttpURLConnection) dataUrl.openConnection();
            // optional default is GET
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            Log.w("Some error occured", e);
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
    public static String postHttpResponse(String dataUrl, HashMap<String, String> postData) {

        StringBuffer responseString = null;
        HttpURLConnection connection = null;
        String inputLine;

        try {
            URL postUrl = new URL(dataUrl);
            String email_id = postData.get("email_id");
            String device_id = postData.get("device_id");
            String status = postData.get("status");

            connection = (HttpURLConnection) postUrl.openConnection();

            String urlParameters = "device_id=" + device_id + "&email_id=" + email_id + "&status=" + status;
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                responseString = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    responseString.append(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace(); //If you want further info on failure...
                return null;
            }
        }
        return responseString.toString();
    }
公共静态字符串postHttpResponse(字符串dataUrl、HashMap postData){
StringBuffer responseString=null;
HttpURLConnection=null;
字符串输入线;
试一试{
URL postrl=新URL(数据URL);
字符串email_id=postData.get(“email_id”);
字符串device_id=postData.get(“device_id”);
字符串状态=postData.get(“状态”);
connection=(HttpURLConnection)postrl.openConnection();
字符串urlParameters=“device_id=“+device_id+”&email_id=“+email_id+”&status=“+status;
connection.setRequestMethod(“POST”);
connection.setDoOutput(真);
DataOutputStream wr=新的DataOutputStream(connection.getOutputStream());
writeBytes(URL参数);
wr.flush();
wr.close();
int responseCode=connection.getResponseCode();
如果(响应代码==200){
BufferedReader in=新的BufferedReader(新的InputStreamReader(connection.getInputStream());
responseString=新的StringBuffer();
而((inputLine=in.readLine())!=null){
responseString.append(输入行);
}
in.close();
}
}捕获(例外e){
e、 printStackTrace();
返回null;
}最后{
试一试{
连接断开();
}捕获(例外e){
e、 printStackTrace();//如果您想了解有关失败的更多信息。。。
返回null;
}
}
返回responseString.toString();
}

您好,我想您应该切换到httpURlConnection。参观 我在这里添加了一个全局类,用于调用webservice和获取json响应

在CallWebService文件中替换此代码,您将得到字符串形式的响应

public class CallWebService {

    private static final String GET="GET";
    private static final String POST="POST";
    private HashMap<String,String> apiParameters;
    private static String WebService;

    public CallWebService(String MethodType, String WebService, HashMap<String, String> apiParameters) throws MethodNotDefinedException {
            if(MethodType!=null) {
                if (MethodType.equalsIgnoreCase(GET)) {
                    if(WebService!=null){
                        this.WebService=WebService;
                        new ExecuteAsyncTask(GET).execute();
                    }else{
                       throw new NullPointerException("Please define webservice url.");
                    }
                } else if(MethodType.equalsIgnoreCase(POST)){
                    if(WebService!=null){
                        if(apiParameters!=null)this.apiParameters=apiParameters;
                        this.WebService=WebService;
                        new ExecuteAsyncTask(POST).execute(apiParameters);
                    }else{
                        throw new NullPointerException("Please define webservice url.");
                    }
                }else{
                    throw new MethodNotDefinedException("Define method for webservice.");
                }
            }else{
                throw new MethodNotDefinedException("Define method for webservice.");
            }
    }

    private class ExecuteAsyncTask extends AsyncTask<HashMap<String,String>,Void,String>{
        String MethodType;
        public ExecuteAsyncTask(String MethodType){
            this.MethodType=MethodType;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            OnStartingService();
        }

        @Override
        protected void onPostExecute(String string) {
            super.onPostExecute(string);
            try {
                OnGettingResult(string);
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (MethodNotDefinedException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(HashMap<String, String>... params) {
            if(MethodType.equalsIgnoreCase(GET))
            return getJSON(WebService,15000);
            else try {
                return getJSONPOST(WebService,params[0]);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public void OnStartingService(){
    }
    public void OnGettingResult(String jsonObject) throws JSONException, MethodNotDefinedException {
    }





    private String getJSON(String url, int timeout) {
        HttpURLConnection c = null;
        try {
            URL u = new URL(url);
            c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setRequestProperty("Content-length", "0");
            c.setUseCaches(false);
            c.setAllowUserInteraction(false);
            c.setConnectTimeout(timeout);
            c.setReadTimeout(timeout);
            c.connect();
            int status = c.getResponseCode();

            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line+"\n");
                    }
                    br.close();
                    System.out.println(sb.toString());
                    return sb.toString();
            }

        } catch (MalformedURLException ex) {
        } catch (IOException ex) {
        }  finally {
            if (c != null) {
                try {
                    c.disconnect();
                } catch (Exception ex) {
                }
            }
        }
        return null;
    }


    private String getJSONPOST(String url1, HashMap<String,String> apiParams) throws IOException, JSONException {
        URL url = new URL(url1);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        String getParams=getQuery(apiParams);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getParams);
        writer.flush();
        writer.close();
        os.close();
        conn.connect();

        int status = conn.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                System.out.println(sb.toString());
                return sb.toString();
        }


        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception ex) {
            }
        }
        return null;
    }




    private String getQuery(HashMap<String,String> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;


        for(Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }
}
公共类CallWebService{
私有静态最终字符串GET=“GET”;
私有静态最终字符串POST=“POST”;
私有HashMap参数;
私有静态字符串Web服务;
public CallWebService(String MethodType、String WebService、HashMap ApipParameters)抛出MethodNotDefinedException{
if(MethodType!=null){
if(MethodType.equalsIgnoreCase(GET)){
if(WebService!=null){
this.WebService=WebService;
新建ExecuteAsyncTask(GET.execute();
}否则{
抛出新的NullPointerException(“请定义webservice url”);
}
}else if(MethodType.equalsIgnoreCase(POST)){
if(WebService!=null){
如果(apipParameters!=null)this.apipParameters=apipParameters;
this.WebService=WebService;
新的ExecuteAsyncTask(POST).execute(apiParameters);
}否则{
抛出新的NullPointerException(“请定义webservice url”);
}
}否则{
抛出新的MethodNotDefinedException(“为webservice定义方法”);
}
}否则{
抛出新的MethodNotDefinedException(“为webservice定义方法”);
}
}
私有类ExecuteAsyncTask扩展异步任务{
字符串方法类型;
public ExecuteAsyncTask(字符串方法类型){
this.MethodType=MethodType;
}
@凌驾
受保护的空位