Java:ConnectException /无法找到或加载Main-Class

时间:2015-06-08 03:07:23

标签: java apache http jar connectexception

简而言之,我只是试图获得一个小型的工作骨架程序,我可以用它来学习Http通信和"感觉"我的方式来弄清楚我最终需要一个更大的计划,我正在努力。这里的特定代码实际上只是Apache库中一个示例的切碎版本。我可以编译Apache网站上列出的示例,但是它们没有正常运行,给出了" java.net.ConnectException"。我认为它与Windows c-blocking这样的程序有关,不能建立连接,我需要以管理员身份运行它。然后我尝试将代码放入可执行的jar文件中,但是我得到了一个Can not-find-or-load-main-class错误。我是一个白痴还是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;
    }
}

2 个答案:

答案 0 :(得分:1)

  

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

这可能是由许多事情引起的。异常消息中有线索......您选择不与我们分享。

  

...“无法找到或加载Main-Class”

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

但是你在你提供的错误消息片段中创建了一个JAR文件加上“Main-Class”提示的事实表明你在创建JAR文件时犯了一个错误;即你使用了错误的名称作为“Main-Class”属性。

鉴于源代码,“Main-Class”属性应为“NewProject.NewProject”。我怀疑你把它设置为其他东西。

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

  

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

Apache库没有任何问题。

答案 1 :(得分: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);
        }
    }

}