Java Apache httpclient 阻塞 GUI

标签 java apache httpclient block

我目前正在使用 Apache 的 http API 开发 HTTP 应用程序,并且正在使用 GUI。在每次 GET 或 POST 请求之后,我想用一些消息更新 GUI TextArea。问题是这些消息是在所有请求完成后才出现的。

我还注意到,如果我在每次请求后在控制台上写入消息,该消息都会出现,但如果我在 GUI 上写入,所有消息都会出现在末尾。

这里是一些代码片段:

GUI 构造函数:

public GUI() {
        initComponents();
        SetMessage.gui = this;
}

SetMessage类:

public class SetMessage implements Runnable{

    public static GUI gui;
    private String msg;

    public SetMessage( String msg){
        synchronized(gui){
            this.msg = msg;
        }
    }

    public void run() {
        gui.setText(msg);
    }

}

GET请求类(每个请求都是由一个线程发出):

public class SendGetReq extends Thread {

private HttpConnection hc = null;
private DefaultHttpClient httpclient = null;
private HttpGet getreq = null;
private int step = -1;
private String returnString = null;

public SendGetReq(HttpConnection hc, DefaultHttpClient httpclient, HttpGet getreq, int step) {
    this.hc = hc;
    this.httpclient = httpclient;
    this.getreq = getreq;
    this.step = step;
}

@Override
public void run() {
   // CODE
}

和 HttpConnection 类(当我按下 GUI 上的按钮时创建该类的实例):

    public class HttpConnection {
        private DefaultHttpClient httpclient = null;
        private HttpGet getreq = null;
        private HttpPost postreq = null;
private SendGetReq tempGet = null;
         // More fields
        private void RandomMethod(){
//Initialize getreq
(tempGet = new SendGetReq(this, httpclient, getreq, 0)).start();
new SetMessage("Message").run();

}

哦! GUI 的 SetText 方法:

public synchronized void setText(String msg){
        if(!"".equals(msg)){
            Date currentDate = new Date();
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(currentDate);
            jTextArea1.append(calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND)+" --- "+msg+"\n");                        
        }
    }

谁能帮我解决这个问题吗?谢谢! }

最佳答案

是的,GUI 的相当标准的行为。您需要在另一个线程中执行 HTTP 请求,然后通知 GUI 线程更新 UI。 Swing 特别要求 UI 从单个线程(准确地说是事件调度线程)更新。

请参阅 SwingUtilities#isEventDispatchThread()SwingUtilities#invokeLater()SwingWorker 类。

关于Java Apache httpclient 阻塞 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7159215/

相关文章:

java - 如何使用带有 Web 身份验证的 apache httpclient 进行 http 发布?

java - 多个java spring应用程序实例访问相同的数据库资源

java - 获取与正则表达式匹配的每个字符串的数组

php - fatal error 调用未定义的函数curl_init()

apache - 如何重写htaccess规则以重定向到css文件

c# - 在可移植 HttpClient 中支持 TLS 1.2 和 1.1

java - 我想在selenium java webdriver中通过xpath选择所有href

java - 如何改变位图的大小?

apache - 在 TOMCAT 7 上安装 Apache Archiva 作为 Web 应用程序

java - Applet + Http Get 向其他 URL 发出请求