Android - HttpClient 执行有自己的想法 - 1 秒或 200 秒

发布于 2024-11-19 16:14:34 字数 5447 浏览 1 评论 0原文

我正在尝试使用 HttpClient 连接到一个 php 页面,该页面登录并传回 sessionid,然后转到一个新页面,使用该 sessionid 并获取与该 sessionid 关联的 mySQL 数据字段。

对于第一个请求,HttpClient 可能需要 1.5 秒、6 秒或 2 分钟。如果第一个请求很慢,则后续请求似乎会更快,反之亦然。

单击 Button 视图时会发生 HttpClient 请求

这是我的代码:

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    name = (TextView)findViewById(R.id.name);
    user = (EditText) findViewById(R.id.user);
    pass = (EditText) findViewById(R.id.pass);
    submit = (Button) findViewById(R.id.button1);
    submit.setOnClickListener(this);
    HttpParams params1 = new BasicHttpParams();
    params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client = new DefaultHttpClient(params1);
    httpclient = new DefaultHttpClient();
    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();
    // Create local HTTP context


}

public void onClick(View v) {
    if (v.getId() == R.id.button1) {
        //submit.setClickable(false);
        String username = user.getText().toString();
        String password = pass.getText().toString();
        String targetURL = "<<<<LOGIN PHP URL>>>>";

        post = new HttpPost(targetURL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        Log.d("params","params added");
        try {
            post.setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Log.d("entity added","entityadded");
        Log.d("preex","PRE EXECUTION");

        localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        //submit.setText("Logging In...");
        new Thread(new Runnable(){
            public void run(){

            try {
                Log.d("pre","pre execute");
                response = client.execute(post,localContext);   
                Log.d("post","post execute");

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            Log.d("post","FIANLLY");
            try {
                input = response.getEntity().getContent();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("response: ",convertStreamToString(input));
            getFullName(localContext);

        }
            }

        }).start();}



}

private void getFullName(final HttpContext context){
    Log.d("called","called");
    String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
    //client1 = new DefaultHttpClient();
    post1 = new HttpPost(targetURL);
    Log.d("","about to call runable....");
//  submit.setText("Obtaining Full Name...");
        try {
            Log.d("pre","CALLING!");
            response = client.execute(post1,context);   
            Log.d("post","called..");

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        Log.d("post","FIANLLY");
        try {
            //submit.setText("Full Name Obtained!...");
            input = response.getEntity().getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Log.d("response: ",convertStreamToString(input));
        outputResponse(input);

    }

}


private void outputResponse(final InputStream in) {
    name.post(new Runnable(){
        public void run(){

            String fullname=convertStreamToString(in);
    name.setText("Full Name is: "+fullname);
        }
    });

}



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();
}

在我设置 Http 版本 1.1 之前,它花费了两倍的时间,但对于我的应用程序来说,速度不可能不可靠。这一切都需要相当快的 WiFi 连接——你能想象 Edge 或 3G 的速度吗?

那么我可以优化什么?

谢谢大家:)


编辑:我做了一个新的测试: http://www.posttestserver.com/ 和事情发生得很快。我当前使用的网址不是我的最终服务器网址,它们适用于不同服务器上的不同网站 - 共享托管,因此,联系我的共享托管网站是否会很慢,并且会与我的 .网络服务器?

再次感谢 !

I'm trying to use HttpClient to connect to a php page that logs in and passes back a sessionid and then goes to a new page, using that sessionid and obtains a mySQL datafield associated with that sessionid.

On the first request, HttpClient can take 1.5 seconds, 6 seconds, or 2 minutes. If the first request was slow, subsequence requests seem to be faster, and visaversa.

The HttpClient request occurs when a Button view is clicked

Here's my code:

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    name = (TextView)findViewById(R.id.name);
    user = (EditText) findViewById(R.id.user);
    pass = (EditText) findViewById(R.id.pass);
    submit = (Button) findViewById(R.id.button1);
    submit.setOnClickListener(this);
    HttpParams params1 = new BasicHttpParams();
    params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client = new DefaultHttpClient(params1);
    httpclient = new DefaultHttpClient();
    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();
    // Create local HTTP context


}

public void onClick(View v) {
    if (v.getId() == R.id.button1) {
        //submit.setClickable(false);
        String username = user.getText().toString();
        String password = pass.getText().toString();
        String targetURL = "<<<<LOGIN PHP URL>>>>";

        post = new HttpPost(targetURL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        Log.d("params","params added");
        try {
            post.setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Log.d("entity added","entityadded");
        Log.d("preex","PRE EXECUTION");

        localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        //submit.setText("Logging In...");
        new Thread(new Runnable(){
            public void run(){

            try {
                Log.d("pre","pre execute");
                response = client.execute(post,localContext);   
                Log.d("post","post execute");

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            Log.d("post","FIANLLY");
            try {
                input = response.getEntity().getContent();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("response: ",convertStreamToString(input));
            getFullName(localContext);

        }
            }

        }).start();}



}

private void getFullName(final HttpContext context){
    Log.d("called","called");
    String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
    //client1 = new DefaultHttpClient();
    post1 = new HttpPost(targetURL);
    Log.d("","about to call runable....");
//  submit.setText("Obtaining Full Name...");
        try {
            Log.d("pre","CALLING!");
            response = client.execute(post1,context);   
            Log.d("post","called..");

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        Log.d("post","FIANLLY");
        try {
            //submit.setText("Full Name Obtained!...");
            input = response.getEntity().getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Log.d("response: ",convertStreamToString(input));
        outputResponse(input);

    }

}


private void outputResponse(final InputStream in) {
    name.post(new Runnable(){
        public void run(){

            String fullname=convertStreamToString(in);
    name.setText("Full Name is: "+fullname);
        }
    });

}



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();
}

Before I set Http version 1.1 it took double the time, but for my application, the speed cannot be unreliable. This is all on a pretty fast WiFi connections -- can you image Edge or 3G speeds??

So what can I optimize?

Thanks everyone:)


EDIT: I did a new test with: http://www.posttestserver.com/ and it happened pretty fast. The urls I'm using currently aren't my final server urls, they are for a different site on a different server -- shared hosting, so could it be that contacting my shared hosting site is just slow and will be compared to my .net server?

Thanks again !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文