关于Android HttpPost请求

时间:2012-12-21 09:07:54

标签: android http-post

我遇到Android HttpPost请求问题。像这样的代码:

@Override
public void onClick(View v) {

                NameValuePair nameValuePair1 = new BasicNameValuePair("name", "zhangsan");
                NameValuePair nameValuePair2 = new BasicNameValuePair("age", "18");
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(nameValuePair1);
                nameValuePairs.add(nameValuePair2);

                try {
                    HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
                    HttpPost httpPost = new HttpPost("http://www.*.cn/test.aspx");
                    httpPost.setEntity(requestHttpEntity);
                    HttpClient httpClient = new DefaultHttpClient();

                    //Using the Http client sends request object
                    try {
                        System.out.println("1111111111111");
                        httpResponse = httpClient.execute(httpPost);
                        System.out.println("2222222222222");
                        httpEntity = httpResponse.getEntity();
                        System.out.println("33333333333333");
                        System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                        System.out.println("44444444444444");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

通过测试,程序可以在Android2.3和模拟器上毫无问题地运行,最终获得正确的输出。

它在Android2.1和模拟器或Android2.2上运行将被困在以下位置。

System.out.println (EntityUtils.toString (httpResponse.getEntity ()));

等了很长时间,偶尔会突然显示应用程序的提示没有响应,偶尔会出现"44444444444444"的输出。但是在正常情况下没有函数"System.out.println (EntityUtils.toString (httpResponse.getEntity ()));"的输出。

所以我分别在带有模拟器的android2.2手机和带模拟器的android2.1手机上进行了一些测试。

测试一:

我将http://www.*.cn/test.aspx更改为http://www.google.com,并且运行正确。

测试二:

我注释了"httpPost.setEntity (requestHttpEntity); "行,然后在代码中请求了没有请求参数的URL。它运行正常。

请给我一个建议!谢谢!

2 个答案:

答案 0 :(得分:1)

将代码移动到Async任务可以使用这些链接执行您的任务。查看herehereherehere

答案 1 :(得分:1)

你需要在一个单独的线程中编写HttpPost。如果用户点击,它将冻结用户界面。请查找示例代码以执行HttpPost。

public class ConnectionManager{
    private Context context;

    public ConnectionManager(Context ctx){
        this.context = ctx;
    }

    public boolean networkInfo(){
        ConnectivityManager connMgr = (ConnectivityManager)this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    public void showAlert(String title,String message){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this.context);

        // set title
        alertDialogBuilder.setTitle(title);

        // set dialog message
        alertDialogBuilder
        .setMessage(message)
        .setCancelable(false)
        .setNegativeButton("OK",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // if this button is clicked, just close
                // the dialog box and do nothing
                dialog.cancel();
            }
        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }
    public String execute_get(String url) {
        // TODO Auto-generated method stub
        HttpResponse response  = null;
        String str_response = "";               

        if(networkInfo()){
            DefaultHttpClient httpsClient = getHTTPSClient();

            try {
                HttpGet httpget = new HttpGet(url);
                response = httpsClient.execute(httpget);
                if (response != null) {
                    str_response = EntityUtils.toString(response.getEntity());
                    Log.d("Connection Manager","Response: "+str_response);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            showAlert("Connection Error","Please connect to wifi/3g to continue");
        }

        return str_response;
    }

    public DefaultHttpClient getHTTPSClient() {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
        DefaultHttpClient httpsClient= new DefaultHttpClient(cm, params);
        return httpsClient;
    }

    public String execute_post(String url,String request){
        HttpResponse response  = null;
        String str_response = "";               
        if(networkInfo()){
            DefaultHttpClient httpsClient = getHTTPSClient();

            try {
                HttpPost httppost = new HttpPost(url);

                List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("jsonData", request));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));   
                response = httpsClient.execute(httppost);

                if (response != null) {
                    str_response = EntityUtils.toString(response.getEntity());
                    Log.d("ConnectionManager", "Response: "+str_response);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            showAlert("Connection Error","Please connect to wifi/3g to continue");
        }
        return str_response;
    }   


}


// Use the above like this 

                              new Thread() {
                    @Override
                    public void run() {
                        try {
                            String input = "Your post data"
                            Log.d("POSTDATA",input);
                            String response = execute_post(URLS.LOGIN_AUTH,input);

                            Message responseMsg = new Message();
                            Bundle b = new Bundle();
                            b.putString("response", response);
                            responseMsg.setData(b);

                            handler.sendMessage(responseMsg);
                        }catch(Exception e){

                        }
                    }
                }.start();