1

所以简而言之,我只是想获得一个小的工作框架程序,我可以用它来了解 Http 通信并“感受”我的方式来弄清楚我最终需要什么来完成我正在工作的更大程序上。这里的这个特定代码实际上只是 Apache 库中示例的切碎版本。我可以编译 Apache 网站上列出的示例,但它们没有正常运行,给出“java.net.ConnectException”。我认为这与 Windows c 阻止这样的程序建立连接有关,并且我需要以管理员身份运行它。然后我尝试获取代码并将其放入可执行的 jar 文件中,但我得到了一个无法找到或加载主类错误。我是白痴还是 Apache 库有点过时/不适合 Win 8/其他?

下面的代码:

package NewProject;


import java.net.Socket;

import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;

class NewProject
{
    public static void main(String[] args) throws Exception
    {
        HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new RequestContent())
            .add(new RequestTargetHost())
            .add(new RequestConnControl())
            .add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpCoreContext coreContext = HttpCoreContext.create();
        HttpHost host = new HttpHost("localhost", 8080);
        coreContext.setTargetHost(host);

        Out os = new Out("TestOut.txt");

        DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
        ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

        try 
        {

            String[] targets = 
            {
                "http://www.google.com/"
            };

            for (int i = 0; i < targets.length; i++) 
            {
                if (!conn.isOpen()) 
                {
                    Socket socket = new Socket(host.getHostName(), host.getPort());
                    conn.bind(socket);
                }
                BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
                os.println(">> Request URI: " + request.getRequestLine().getUri());

                httpexecutor.preProcess(request, httpproc, coreContext);
                HttpResponse response = httpexecutor.execute(request, conn, coreContext);
                httpexecutor.postProcess(response, httpproc, coreContext);

                os.println("<< Response: " + response.getStatusLine());
                os.println(EntityUtils.toString(response.getEntity()));
                os.println("==============");

                if (!connStrategy.keepAlive(response, coreContext)) 
                {
                    conn.close();
                }
                else 
                {
                    os.println("Connection kept alive...");
                }
            }
        }
        catch (IndexOutOfBoundsException iob)
        {
            os.println("What happened here?");
        }
        finally
        {
            conn.close();
        }

        return;
    }
}
4

2 回答 2

1

...他们没有正常运行,给出“java.net.ConnectException”

这可能是由很多事情造成的。异常消息中有一些线索……您选择不与我们分享。

...“无法找到或加载主类”

再次有多种可能的原因,并且异常消息中有线索......您选择不与我们分享。

但是,您已经创建了一个 JAR 文件以及您提供的错误消息片段中的“Main-Class”提示,这表明您在创建 JAR 文件时犯了一个错误;即您为“Main-Class”属性使用了错误的名称。

鉴于该源代码,“Main-Class”属性应该是“NewProject.NewProject”。我怀疑您将其设置为其他内容。

第二种可能性是您没有正确处理对 Apache 库的依赖关系。Apache 类需要位于 JAR 文件指定的类路径中。(您不能使用-cp参数或使用$CLASSPATH启动时java -jar。)


我是白痴还是 Apache 库有点过时/不适合 Win 8/其他?

Apache 库没有任何问题。

于 2015-06-08T04:07:15.297 回答
0

您发布的代码似乎有点低级(例如直接与 Socket 连接交互)。下面发布的代码应该为您提供您正在寻找的内容。使用的类还为您提供了很多设置和获取http 参数(例如标头、超时等)的方法。

package org.yaorma.example.http.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClientExample {

    public static void main(String[] args) throws Exception {
        String response;
        response = get("http://www.google.com");
        System.out.println("RESPONSE FROM GET -----------------------------------------");
        System.out.println(response);
        response = post("http://httpbin.org/post", "This is the message I posted to httpbin.org/post");
        System.out.println("RESPONSE FROM POST -----------------------------------------");
        System.out.println(response);
    }

    /**
     * Method to post a request to a given URL.
     */
    public static String post(String urlString, String message) {
        try {
            // get a connection
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // set the parameters
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            // send the message
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(message);
            writer.flush();
            writer.close();
            os.close();
            // get the response
            conn.connect();
            InputStream content = (InputStream) conn.getInputStream();
            // read the response
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            String rtn = "";
            String line;
            while ((line = in.readLine()) != null) {
                rtn += line + "\n";
            }
            return rtn;
        } catch (Exception exp) {
            throw new RuntimeException(exp);
        }
    }

    /**
     * Method to do a get from a given URL.
     */
    public static String get(String urlString) {
        try {
            // get a connection
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // set the parameters
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            // get the response
            conn.connect();
            InputStream content = (InputStream) conn.getInputStream();
            // read the response
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            String rtn = "";
            String line;
            while ((line = in.readLine()) != null) {
                rtn += line + "\n";
            }
            return rtn;
        } catch (Exception exp) {
            throw new RuntimeException(exp);
        }
    }

}
于 2015-06-08T04:26:04.057 回答