为何没响应内容,难道是http请求内容不对吗?import java.net.*;
import java.io.*;
public class HTTPClient {
  String host="www.javathinker.org";
  int port=80;
  Socket socket;
  
  public void createSocket()throws Exception{
    socket=new Socket("www.163.com",80);
  }
    public void communicate()throws Exception{
  StringBuffer sb = new StringBuffer("GET / HTTP/1.1\r\n");
sb.append("Host: www.163.com\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Accept: */*\r\n");    //发出HTTP请求
    OutputStream socketOut=socket.getOutputStream();
    socketOut.write(sb.toString().getBytes());
    socket.shutdownOutput();  //关闭输出流
       
    //接收响应结果
    System.out.println(socket);    InputStream socketIn=socket.getInputStream();
    BufferedReader br=new BufferedReader(new InputStreamReader(socketIn));
    String data;
    while((data=br.readLine())!=null){
      System.out.println(data);
    }
    socket.close();
  }
  
  public static void main(String args[])throws Exception{
    HTTPClient client=new HTTPClient();
    client.createSocket();
    client.communicate();
  } 
}

解决方案 »

  1.   

    不是这样通信的吧
    你想他返回什么呢?服务器端可能根本就没接受你的请求
    自己写个服务器端就知道了他是怎么接受的我想LZ是想抓取页面吗?
    public static void main(String[] a) throws UnknownHostException, IOException{
    String sLine = "";
    InputStream in;
    java.net.URL url = new java.net.URL("http://www.google.cn/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(in)); while ((sLine = reader.readLine()) != null)
    {
     System.out.println(sLine);
    }

    }
      

  2.   

    package test;import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;import org.apache.log4j.Logger;/**
     * <pre>
     * HTTP请求代理类
     * </pre>
     * 
     * @author benl
     * @version 1.0, 2007-7-3
     */
    public class HttpRequestProxy
    {
        /**
         * 连接超时
         */
        private static int connectTimeOut = 5000;    /**
         * 读取数据超时
         */
        private static int readTimeOut = 10000;    /**
         * 请求编码
         */
        private static String requestEncoding = "GBK";    private static Logger logger = Logger.getLogger(HttpRequestProxy.class);    /**
         * <pre>
         * 发送带参数的GET的HTTP请求
         * </pre>
         * 
         * @param reqUrl HTTP请求URL
         * @param parameters 参数映射表
         * @return HTTP响应的字符串
         */
        public static String doGet(String reqUrl, Map parameters,
                String recvEncoding)
        {
            HttpURLConnection url_con = null;
            String responseContent = null;
            try
            {
                StringBuffer params = new StringBuffer();
                for (Iterator iter = parameters.entrySet().iterator(); iter
                        .hasNext();)
                {
                    Entry element = (Entry) iter.next();
                    params.append(element.getKey().toString());
                    params.append("=");
                    params.append(URLEncoder.encode(element.getValue().toString(),
                            HttpRequestProxy.requestEncoding));
                    params.append("&");
                }            if (params.length() > 0)
                {
                    params = params.deleteCharAt(params.length() - 1);
                }            URL url = new URL(reqUrl);
                url_con = (HttpURLConnection) url.openConnection();
                url_con.setRequestMethod("GET");
                System.setProperty("sun.net.client.defaultConnectTimeout", String
                        .valueOf(HttpRequestProxy.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
                System.setProperty("sun.net.client.defaultReadTimeout", String
                        .valueOf(HttpRequestProxy.readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
                // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
                // 1.5换成这个,连接超时
                // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
                url_con.setDoOutput(true);
                byte[] b = params.toString().getBytes();
                url_con.getOutputStream().write(b, 0, b.length);
                url_con.getOutputStream().flush();
                url_con.getOutputStream().close();            InputStream in = url_con.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                        recvEncoding));
                String tempLine = rd.readLine();
                StringBuffer temp = new StringBuffer();
                String crlf=System.getProperty("line.separator");
                while (tempLine != null)
                {
                    temp.append(tempLine);
                    temp.append(crlf);
                    tempLine = rd.readLine();
                }
                responseContent = temp.toString();
                rd.close();
                in.close();
            }
            catch (IOException e)
            {
                logger.error("网络故障", e);
            }
            finally
            {
                if (url_con != null)
                {
                    url_con.disconnect();
                }
            }        return responseContent;
        }    /**
         * <pre>
         * 发送不带参数的GET的HTTP请求
         * </pre>
         * 
         * @param reqUrl HTTP请求URL
         * @return HTTP响应的字符串
         */
      

  3.   

       public static String doGet(String reqUrl, String recvEncoding)
        {
            HttpURLConnection url_con = null;
            String responseContent = null;
            try
            {
                StringBuffer params = new StringBuffer();
                String queryUrl = reqUrl;
                int paramIndex = reqUrl.indexOf("?");            if (paramIndex > 0)
                {
                    queryUrl = reqUrl.substring(0, paramIndex);
                    String parameters = reqUrl.substring(paramIndex + 1, reqUrl
                            .length());
                    String[] paramArray = parameters.split("&");
                    for (int i = 0; i < paramArray.length; i++)
                    {
                        String string = paramArray[i];
                        int index = string.indexOf("=");
                        if (index > 0)
                        {
                            String parameter = string.substring(0, index);
                            String value = string.substring(index + 1, string
                                    .length());
                            params.append(parameter);
                            params.append("=");
                            params.append(URLEncoder.encode(value,
                                    HttpRequestProxy.requestEncoding));
                            params.append("&");
                        }
                    }                params = params.deleteCharAt(params.length() - 1);
                }            URL url = new URL(queryUrl);
                url_con = (HttpURLConnection) url.openConnection();
                url_con.setRequestMethod("GET");
                System.setProperty("sun.net.client.defaultConnectTimeout", String
                        .valueOf(HttpRequestProxy.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
                System.setProperty("sun.net.client.defaultReadTimeout", String
                        .valueOf(HttpRequestProxy.readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
                // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
                // 1.5换成这个,连接超时
                // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
                url_con.setDoOutput(true);
                byte[] b = params.toString().getBytes();
                url_con.getOutputStream().write(b, 0, b.length);
                url_con.getOutputStream().flush();
                url_con.getOutputStream().close();
                InputStream in = url_con.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                        recvEncoding));
                String tempLine = rd.readLine();
                StringBuffer temp = new StringBuffer();
                String crlf=System.getProperty("line.separator");
                while (tempLine != null)
                {
                    temp.append(tempLine);
                    temp.append(crlf);
                    tempLine = rd.readLine();
                }
                responseContent = temp.toString();
                rd.close();
                in.close();
            }
            catch (IOException e)
            {
                logger.error("网络故障", e);
            }
            finally
            {
                if (url_con != null)
                {
                    url_con.disconnect();
                }
            }        return responseContent;
        }    /**
         * <pre>
         * 发送带参数的POST的HTTP请求
         * </pre>
         * 
         * @param reqUrl HTTP请求URL
         * @param parameters 参数映射表
         * @return HTTP响应的字符串
         */
        public static String doPost(String reqUrl, Map parameters,
                String recvEncoding)
        {
            HttpURLConnection url_con = null;
            String responseContent = null;
            try
            {
                StringBuffer params = new StringBuffer();
                for (Iterator iter = parameters.entrySet().iterator(); iter
                        .hasNext();)
                {
                    Entry element = (Entry) iter.next();
                    params.append(element.getKey().toString());
                    params.append("=");
                    params.append(URLEncoder.encode(element.getValue().toString(),
                            HttpRequestProxy.requestEncoding));
                    params.append("&");
                }            if (params.length() > 0)
                {
                    params = params.deleteCharAt(params.length() - 1);
                }            URL url = new URL(reqUrl);
                url_con = (HttpURLConnection) url.openConnection();
                url_con.setRequestMethod("POST");
                System.setProperty("sun.net.client.defaultConnectTimeout", String
                        .valueOf(HttpRequestProxy.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
                System.setProperty("sun.net.client.defaultReadTimeout", String
                        .valueOf(HttpRequestProxy.readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
                // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
                // 1.5换成这个,连接超时
                // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
                url_con.setDoOutput(true);
                byte[] b = params.toString().getBytes();
                url_con.getOutputStream().write(b, 0, b.length);
                url_con.getOutputStream().flush();
                url_con.getOutputStream().close();            InputStream in = url_con.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                        recvEncoding));
                String tempLine = rd.readLine();
                StringBuffer tempStr = new StringBuffer();
                String crlf=System.getProperty("line.separator");
                while (tempLine != null)
                {
                    tempStr.append(tempLine);
                    tempStr.append(crlf);
                    tempLine = rd.readLine();
                }
                responseContent = tempStr.toString();
                rd.close();
                in.close();
            }
            catch (IOException e)
            {
                logger.error("网络故障", e);
            }
            finally
            {
                if (url_con != null)
                {
                    url_con.disconnect();
                }
            }
            return responseContent;
        }    /**
         * @return 连接超时(毫秒)
         * @see com.hengpeng.common.web.HttpRequestProxy#connectTimeOut
         */
        public static int getConnectTimeOut()
        {
            return HttpRequestProxy.connectTimeOut;
        }    /**
         * @return 读取数据超时(毫秒)
         * @see com.hengpeng.common.web.HttpRequestProxy#readTimeOut
         */
        public static int getReadTimeOut()
        {
            return HttpRequestProxy.readTimeOut;
        }    /**
         * @return 请求编码
         * @see com.hengpeng.common.web.HttpRequestProxy#requestEncoding
         */
        public static String getRequestEncoding()
        {
            return requestEncoding;
        }    /**
         * @param connectTimeOut 连接超时(毫秒)
         * @see com.hengpeng.common.web.HttpRequestProxy#connectTimeOut
         */
        public static void setConnectTimeOut(int connectTimeOut)
        {
            HttpRequestProxy.connectTimeOut = connectTimeOut;
        }    /**
         * @param readTimeOut 读取数据超时(毫秒)
         * @see com.hengpeng.common.web.HttpRequestProxy#readTimeOut
         */
        public static void setReadTimeOut(int readTimeOut)
        {
            HttpRequestProxy.readTimeOut = readTimeOut;
        }    /**
         * @param requestEncoding 请求编码
         * @see com.hengpeng.common.web.HttpRequestProxy#requestEncoding
         */
        public static void setRequestEncoding(String requestEncoding)
        {
            HttpRequestProxy.requestEncoding = requestEncoding;
        }
        
        public static void main(String[] args)
        {
            Map map = new HashMap();
    //        map.put("_RECONNECT", "YES");
    //        map.put("_FUNCTION", "WWW_GET_REPORT");
    //        map.put("_REPORT", "RM07MLBS");
    //        map.put("SELC_WERKS-LOW", "V001");
    //        map.put("SELC_MATNR-LOW", "10000001");
    //       
            String temp = HttpRequestProxy.doPost("http://lhaig:82/scripts/wgate/xgwfc/!?_FUNCTION=WWW_GET_SELSCREEN&_REPORT=RM07MLBS", map, "UTF-8");
            System.out.println("返回的消息是:"+temp);
            
        }
    }
      

  4.   

    我主要是想看看 http请求发送的内容,虽然都有介绍,但是没跑通过。
      

  5.   

    String temp = HttpRequestProxy.doPost("http://163.com", map, "UTF-8"); 
      

  6.   

    知道哪里错了 
    sb.append("Accept: */*\r\n\r\n");消息的最后一行在加个回车,发到自己建的tomcat服务 可以返回正常数据了。但是像访问163,baidu,google等都没反应,可能做了什么过滤。不知道 望哪个达人帮忙解答,谢谢。
      

  7.   

    sunxing007的一个代码可以读到百度的页面。
    package socket;import java.io.*;
    import java.net.*;public class MyHttpClient {
    public static void main(String[] args) throws Exception{
    InetAddress inet = InetAddress.getByName("www.baidu.com");
    System.out.println(inet.getHostAddress());
    Socket socket = new Socket(inet.getHostAddress(),80);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    PrintWriter writer = new PrintWriter(out);
    writer.println("GET /home.html HTTP/1.1");//home.html是关于百度的页面
    writer.println("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
    writer.println("Accept-Language: en-us,zh-cn;q=0.5");
    writer.println("Accept-Encoding: gzip, deflate");
    writer.println("Host: www.baidu.com");
    writer.println("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
    writer.println("Connection: Keep-Alive");
    writer.println();
    writer.flush();
    String line = reader.readLine();
    while(line!=null){
    System.out.println(line);
    line = reader.readLine();
    }
    reader.close();
    writer.close();
    }
    }你看看是不是你要的效果。
      

  8.   

    呵呵,你对协议没有理解透;
    看看这一句
     sb.append("Accept: */*\r\n");后面增加一句就行了
     sb.append("\r\n");因为http协议的头(header),是以空行作为结束标记的。OVER,建议你再去看看http的协议。