Java 在Android开发中,如何在没有BasicNameValuePair的情况下将数据发送到PHP脚本

Java 在Android开发中,如何在没有BasicNameValuePair的情况下将数据发送到PHP脚本,java,php,android,Java,Php,Android,我正在使用一些在线教程学习Android。除了这个,我所有的java类都很好 @覆盖 受保护的Void doInBackground(Void…参数){ ArrayList dataToSend=新的ArrayList(); 添加(新的BasicNameValuePair(“email”,user.userEmail)); 添加(新的BasicNameValuePair(“fname”,user.firstName)); 添加(新的BasicNameValuePair(“lname”,user

我正在使用一些在线教程学习Android。除了这个,我所有的java类都很好

@覆盖
受保护的Void doInBackground(Void…参数){
ArrayList dataToSend=新的ArrayList();
添加(新的BasicNameValuePair(“email”,user.userEmail));
添加(新的BasicNameValuePair(“fname”,user.firstName));
添加(新的BasicNameValuePair(“lname”,user.lastName));
添加(新的BasicNameValuePair(“密码”,user.password));
HttpParams httpRequestParams=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,连接超时);
HttpConnectionParams.setSoTimeout(httpRequestParams,连接超时);
HttpClient客户端=新的默认HttpClient(httpRequestParams);
HttpPost=newhttppost(服务器地址+“register.php”);
试一试{
post.setEntity(新的URLEncodedFormatEntity(dataToSend));
客户。执行(post);
}捕获(例外e){
e、 printStackTrace();
}
返回null;

}
Httpclient
不推荐使用
HttpsURLConnection

尝试在Android中使用
volley
通过网络发送数据

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", "Androidhive");
                params.put("email", "abc@androidhive.info");
                params.put("password", "password123");

                return params;
            }

        };
JsonObjectRequest JSONObjectReq=新的JsonObjectRequest(Method.POST,
url,空,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
Log.d(TAG,response.toString());
pDialog.hide();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
d(标记“Error:+Error.getMessage());
pDialog.hide();
}
}) {
@凌驾
受保护的映射getParams(){
Map params=新的HashMap();
参数put(“名称”、“Androidhive”);
参数put(“电子邮件”)abc@androidhive.info");
参数put(“密码”、“密码123”);
返回参数;
}
};

Httpclient
不推荐使用
HttpsURLConnection

尝试在Android中使用
volley
通过网络发送数据

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", "Androidhive");
                params.put("email", "abc@androidhive.info");
                params.put("password", "password123");

                return params;
            }

        };
JsonObjectRequest JSONObjectReq=新的JsonObjectRequest(Method.POST,
url,空,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
Log.d(TAG,response.toString());
pDialog.hide();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
d(标记“Error:+Error.getMessage());
pDialog.hide();
}
}) {
@凌驾
受保护的映射getParams(){
Map params=新的HashMap();
参数put(“名称”、“Androidhive”);
参数put(“电子邮件”)abc@androidhive.info");
参数put(“密码”、“密码123”);
返回参数;
}
};

最新版本的android sdk不推荐使用Httpclient 改用截击,参见此处


最新版本的android sdk不推荐使用Httpclient 改用截击,参见此处


您应该使用最流行的网络库,如Reformation或volley,而不是使用android HttpClient不推荐的方法。改型很容易使用。您可以从这里开始:


您应该使用最流行的网络库,如Reformation或volley,而不是使用android HttpClient不推荐的方法。改型很容易使用。您可以从这里开始:


创建一个新类。i、 RestClient.java

public class RestClient {


    private static String SERVICE_URL;

    private ArrayList<NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private int responseCode;
    private String message;

    private String response;

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RestClient(String serviceMethod)
    {
        SERVICE_URL = serviceMethod;
        //this.serviceMethod = serviceMethod;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public String Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                //SERVICE_URL +=serviceMethod;
                HttpGet request = new HttpGet(SERVICE_URL + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, SERVICE_URL);
                break;
            }
            case POST:
            {
                //SERVICE_URL +=serviceMethod;
                HttpPost request = new HttpPost(SERVICE_URL);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, SERVICE_URL);
                break;
            }
        }
        return response;
    }

    private String executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }
            SERVICE_URL+=SERVICE_URL;
        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }

        return response;
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }}

对于GET方法,只需将“client.Execute(RequestMethod.POST)”替换为“client.Execute(RequestMethod.GET)”

创建一个新类。i、 RestClient.java

public class RestClient {


    private static String SERVICE_URL;

    private ArrayList<NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private int responseCode;
    private String message;

    private String response;

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RestClient(String serviceMethod)
    {
        SERVICE_URL = serviceMethod;
        //this.serviceMethod = serviceMethod;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public String Execute(RequestMethod method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                //SERVICE_URL +=serviceMethod;
                HttpGet request = new HttpGet(SERVICE_URL + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, SERVICE_URL);
                break;
            }
            case POST:
            {
                //SERVICE_URL +=serviceMethod;
                HttpPost request = new HttpPost(SERVICE_URL);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, SERVICE_URL);
                break;
            }
        }
        return response;
    }

    private String executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }
            SERVICE_URL+=SERVICE_URL;
        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }

        return response;
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }}

对于GET方法,只需将“client.Execute(RequestMethod.POST)”替换为“client.Execute(RequestMethod.GET)”

HttpClient不推荐使用HttpClient不推荐使用NameValuePair不推荐使用tooNameValuePair不推荐使用tooNameValuePair不推荐使用tooNameValuePair不推荐使用too@MwasuseLibrary'org.apache.http.legacy'NameValuePair已被弃用too@MwasuseLibrary'org.apache.http.legacy'