简体   繁体   English

正确的HTTP客户端方法

[英]Proper HTTP Client method

I'm trying to run a method that I created, but it won't run more than once. 我正在尝试运行自己创建的方法,但不会多次运行。 I think my problem is that I'm never releasing the connection. 我认为我的问题是我从未释放连接。

I tried to follow this tutorial but some of the methods don't work and I don't know why. 我试图按照本教程进行操作,但是某些方法不起作用,我也不知道为什么。 http://hc.apache.org/httpclient-3.x/tutorial.html http://hc.apache.org/httpclient-3.x/tutorial.html

public String sendMessage(String username, Editable message){

        BufferedReader in = null;
        String data = null;
        try{


            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message);

            HttpPost post_request = new HttpPost();
            post_request.setURI(website);


            HttpGet request = new HttpGet();

            request.setURI(website);
            //executing actual request
                HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) != null) {
                sb.append(l);

            }
            in.close();
            data = sb.toString();
            return data;
        }catch (Exception e){
            return "ERROR";
        }

        }

First of all, do you know that the post_request never get used? 首先,您知道post_request永远不会被使用吗? Only the GET method ( request ) is send to the server. 仅GET方法( request )被发送到服务器。

Anyway, here is my code which exactly copies yours (only Editable is String in my case) and should be compilable and runnable as is. 无论如何,这是我的代码,它精确地复制了您的代码(在我的情况下,只有Editable是String),并且应该可以编译和运行。 For me it works. 对我来说,它有效。 Every time I click the button the GET request is performed. 每次我单击按钮时,都会执行GET request

package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;


public class NewJFrame extends javax.swing.JFrame {

  /** Creates new form NewJFrame */
  public NewJFrame() {
    initComponents();
  }


  public String sendMessage(String username, String message){

    BufferedReader in = null;
    String data = null;
    try{


        HttpClient client = new DefaultHttpClient();
        URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message);

        //!!!this is never used
        HttpPost post_request = new HttpPost();
        post_request.setURI(website);


        HttpGet request = new HttpGet();

        request.setURI(website);
        //executing actual request
            HttpResponse response = client.execute(request);

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");
        while ((l = in.readLine()) != null) {
            sb.append(l);

        }
        in.close();

        data = sb.toString();
        System.out.println("Success:\n" + data);


        return data;
    }catch (Exception e){
        return "ERROR";
    }

  }


  @SuppressWarnings("unchecked")
  private void initComponents() {

    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(layout.createSequentialGroup()
            .add(64, 64, 64)
            .add(jButton1)
            .addContainerGap(239, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(layout.createSequentialGroup()
            .add(58, 58, 58)
            .add(jButton1)
            .addContainerGap(213, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    sendMessage("ondra", "textX");
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
  }

  private javax.swing.JButton jButton1;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM