`
y806839048
  • 浏览: 1119042 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

http

阅读更多
package com.ces.zwww.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author bogege
*
*/
public class HttpClient {

private String url;
private String reportMethod;
private boolean isOutPut = true;
private boolean isInput = true;
private boolean allowUserInteraction = true;
private BufferedReader reader;

public HttpClient() {

}

public HttpClient(String url, String reportMethod, boolean... otherParam) {
this.url = url;
this.reportMethod = reportMethod;
if (otherParam.length > 0) {
int len = otherParam.length;
for (int i = 0; i < len; i++) {
if (len == 1)
isOutPut = otherParam[0];
if (len == 2) {
isOutPut = otherParam[0];
isInput = otherParam[1];
}
if (len == 3) {
isOutPut = otherParam[0];
isInput = otherParam[1];
allowUserInteraction = otherParam[2];
}
}
}
}
/**
* 获取返回的字符串
* @return
* @throws Exception
*/
public String getResponseData() throws Exception {
try {
String strMessage = null;
StringBuffer buffer = new StringBuffer();
HttpURLConnection httpConnection = getHttpCon();
if(httpConnection == null ){
return strMessage;
}
InputStream inputStream = httpConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((strMessage = reader.readLine()) != null) {
buffer.append(strMessage);
}
closeHttpCon(httpConnection);
return buffer.toString();
} catch (Exception e) {
throw e;
} finally{
if(reader != null){
reader.close();
}
}
}

/**
* 获取连接
* @param url
*            请求的路径
* @param reportMethod
*            请求的方法 post,get等
* @return
*/
private HttpURLConnection getHttpCon() throws Exception {
try {
URL u = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) u
.openConnection();
httpConnection.setRequestMethod(reportMethod);
httpConnection.setDoOutput(isOutPut);
httpConnection.setDoInput(isInput);
httpConnection.setAllowUserInteraction(allowUserInteraction);
int responseCode = httpConnection.getResponseCode(); 
if (responseCode >= 400) {
throw new Exception("responseCode:"+responseCode);
}
return httpConnection;
} catch (MalformedURLException e) {
throw e;
} catch (IOException e) {
throw e;
}
}

private void closeHttpCon(HttpURLConnection httpConnection) {
httpConnection.disconnect();
}

public boolean isOutPut() {
return isOutPut;
}

public void setOutPut(boolean isOutPut) {
this.isOutPut = isOutPut;
}

public boolean isInput() {
return isInput;
}

public void setInput(boolean isInput) {
this.isInput = isInput;
}

public boolean isAllowUserInteraction() {
return allowUserInteraction;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getReportMethod() {
return reportMethod;
}

public void setReportMethod(String reportMethod) {
this.reportMethod = reportMethod;
}

public void setAllowUserInteraction(boolean allowUserInteraction) {
this.allowUserInteraction = allowUserInteraction;
}

}






package com.ces.zwww.utils;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;



/**
*
* @author bogege
*/
public class HttpServer extends Thread{

private File documentRootDirectory;
private String indexFileName = "index.html";
private ServerSocket server;
private int numThreads = 50;

public HttpServer(File documentRootDirectory, int port, String indexFileName)
throws IOException {
if (!documentRootDirectory.isDirectory()) {
throw new IOException(documentRootDirectory + " does not exist as a directory ");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}

private HttpServer(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.html");
}

public void run() {
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(new RequestProcessor(documentRootDirectory, indexFileName));
t.start();
}
System.out.println("Accepting connection on port " + server.getLocalPort());
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept();
RequestProcessor.processRequest(request);
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
File docroot;
try {
docroot = new File("D:\\temp");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: java HttpServer docroot port indexfile");
return;
}

int port;
try {
port = Integer.parseInt(args[1]);
if (port < 0 || port > 65535) {
port = 80;
}
} catch (Exception e) {
port = 80;
}

try {
HttpServer webserver = new HttpServer(docroot, port);
webserver.start();
} catch (IOException e) {
System.out.println("Server could not start because of an " + e.getClass());
System.out.println(e);
}

}

}





package com.ces.zwww.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

import com.ces.zwww.entity.Tbresource;

/**
*
* @author bogege
*
*/
public class RequestProcessor implements Runnable{

private static List pool=new LinkedList(); 
    private File documentRootDirectory; 
    private String indexFileName="index.html"; 
   
    public RequestProcessor(File documentRootDirectory,String indexFileName) { 
        if (documentRootDirectory.isFile()) { 
            throw new IllegalArgumentException(); 
        } 
        this.documentRootDirectory=documentRootDirectory; 
        try {
            this.documentRootDirectory=documentRootDirectory.getCanonicalFile(); 
        } catch (IOException e) { 
        } 
        if (indexFileName!=null) { 
            this.indexFileName=indexFileName; 
        } 
    } 
     
    public static void processRequest(Socket request) { 
        synchronized (pool) { 
            pool.add(pool.size(),request); 
            pool.notifyAll(); 
        } 
    } 
   
    @Override
    public void run() {
    //安全性检测 
      String root=documentRootDirectory.getPath(); 
      while (true) { 
          Socket connection; 
          synchronized (pool) { 
              while (pool.isEmpty()) { 
                  try { 
                      pool.wait(); 
                  } catch (InterruptedException e) { 
                  e.printStackTrace();
                  }
              }
              connection=(Socket)pool.remove(0);
          }
          try { 
              String fileName; 
              String contentType; 
              OutputStream raw = new BufferedOutputStream(connection.getOutputStream()); 
              Writer out = new OutputStreamWriter(raw, "UTF-8"); 
 
              Reader in=new InputStreamReader(new BufferedInputStream(connection.getInputStream())); 
              StringBuffer request=new StringBuffer(80); 
              //刚进来的时候肯定是空,一直读,读到最后
              while (true) { 
                  int c=in.read(); 
                  if (c=='\t'||c=='\n'||c==-1) { 
                      break; 
                  } 
                  request.append((char)c); 
              } 
              String get=request.toString(); 
              //记录日志 
              System.out.println(get); 
               
              StringTokenizer st=new StringTokenizer(get); 
              String method=st.nextToken(); 
              String version=""; 
              ///输入中传要的方法,拿出来匹配,再输出
              if ("GET".equals(method)) { 
              Tbresource tb = new Tbresource();
              tb.setId("test123");
              tb.setIp("1.1.1.1");
              //tb.setIsfavorite(1);
              //tb.setIsnetdevice(0);
            // tb.setResourceid("1dsf-23");
            // tb.setResourcename("資源1");
            /// tb.setResourcestatus("1");
            // tb.setResourcetype("213");
             
              out.write("HTTP/1.0 200 OK\r\n"); 
              out.write("Date: 2014-01-01\r\n"); 
                  out.write("Server: JHTTP 1.0\r\n"); 
                  out.write("Content-Type: text/html\r\n\r\n"); 
             
              out.write(JsonUtil.objectToJsonStr(tb));
              out.flush();
              }
          } catch (IOException e) { 
          }finally{ 
              try { 
                  connection.close(); 
              } catch (IOException e2) { 
              } 
               
          } 
      } 
    }
     
//    @Override
//    public void run() { 
//        //安全性检测 
//        String root=documentRootDirectory.getPath(); 
//         
//        while (true) { 
//            Socket connection; 
//            synchronized (pool) { 
//                while (pool.isEmpty()) { 
//                    try { 
//                        pool.wait(); 
//                    } catch (InterruptedException e) { 
//                    e.printStackTrace();
//                    }
//                }
//                connection=(Socket)pool.remove(0);
//            }
//            try { 
//                String fileName; 
//                String contentType; 
//                OutputStream raw = new BufferedOutputStream(connection.getOutputStream()); 
//                Writer out = new OutputStreamWriter(raw, "UTF-8"); 
//   
//                Reader in=new InputStreamReader(new BufferedInputStream(connection.getInputStream())); 
//                StringBuffer request=new StringBuffer(80); 
//                while (true) { 
//                    int c=in.read(); 
//                    if (c=='\t'||c=='\n'||c==-1) { 
//                        break; 
//                    } 
//                    request.append((char)c); 
//                } 
//               
//                String get=request.toString(); 
//              
//                //记录日志 
//                System.out.println(get); 
//                 
//                StringTokenizer st=new StringTokenizer(get); 
//                String method=st.nextToken(); 
//                String version=""; 
//                if ("GET".equals(method)) { 
//                    fileName=st.nextToken(); 
//                    if (fileName.endsWith("/")) { 
//                        fileName+=indexFileName; 
//                    } 
//                    contentType=guessContentTypeFromName(fileName); 
//                    if (st.hasMoreTokens()) { 
//                        version=st.nextToken(); 
//                    } 
//                     
//                    File theFile=new File(documentRootDirectory,fileName.substring(1,fileName.length())); 
//                    if (theFile.canRead()&&theFile.getCanonicalPath().startsWith(root)) { 
//                        DataInputStream fis=new DataInputStream(new BufferedInputStream(new FileInputStream(theFile))); 
//                        byte[] theData=new byte[(int)theFile.length()]; 
//                        fis.readFully(theData); 
//                        fis.close(); 
//                        if (version.startsWith("HTTP")) { 
//                            out.write("HTTP/1.0 200 OK\r\n"); 
//                            Date now=new Date(); 
//                            out.write("Date: "+now+"\r\n"); 
//                            out.write("Server: JHTTP 1.0\r\n"); 
//                            out.write("Content-length: "+theData.length+"\r\n"); 
//                            out.write("Content-Type: "+contentType+"\r\n\r\n"); 
//                            out.flush(); 
//                        } 
//                        raw.write(theData); 
//                        raw.flush(); 
//                    }else { 
//                        if (version.startsWith("HTTP ")) { 
//                            out.write("HTTP/1.0 404 File Not Found\r\n"); 
//                            Date now=new Date(); 
//                            out.write("Date: "+now+"\r\n"); 
//                            out.write("Server: JHTTP 1.0\r\n"); 
//                            out.write("Content-Type: text/html\r\n\r\n"); 
//                            out.flush(); 
//                        } 
//                        out.write("<HTML>\r\n"); 
//                        out.write("<HEAD><TITLE>File Not Found</TITLE></HRAD>\r\n"); 
//                        out.write("<BODY>\r\n"); 
//                        out.write("<H1>HTTP Error 404: File Not Found</H1>"); 
//                        out.write("</BODY></HTML>\r\n"); 
//                    } 
//                }else {//方法不等于"GET" 
//                    if (version.startsWith("HTTP ")) { 
//                        out.write("HTTP/1.0 501 Not Implemented\r\n"); 
//                        Date now=new Date(); 
//                        out.write("Date: "+now+"\r\n"); 
//                        out.write("Server: JHTTP 1.0\r\n"); 
//                        out.write("Content-Type: text/html\r\n\r\n"); 
//                        out.flush(); 
//                    } 
//                    out.write("<HTML>\r\n"); 
//                    out.write("<HEAD><TITLE>Not Implemented</TITLE></HRAD>\r\n"); 
//                    out.write("<BODY>\r\n"); 
//                    out.write("<H1>HTTP Error 501: Not Implemented</H1>"); 
//                    out.write("</BODY></HTML>\r\n"); 
//                } 
//                 
//            } catch (IOException e) { 
//            }finally{ 
//                try { 
//                    connection.close(); 
//                } catch (IOException e2) { 
//                } 
//                 
//            } 
//        } 
//    } 
     
    public static String guessContentTypeFromName(String name) { 
        if (name.endsWith(".html")||name.endsWith(".htm")) { 
            return "text/html"; 
        }else if (name.endsWith(".txt")||name.endsWith(".java")) { 
            return "text/plain"; 
        }else if (name.endsWith(".gif")) { 
            return "image/gif"; 
        }else if (name.endsWith(".class")) { 
            return "application/octet-stream"; 
        }else if (name.endsWith(".jpg")||name.endsWith(".jpeg")) { 
            return "image/jpeg"; 
        }else { 
            return "text/plain"; 
        } 
    }
}




另外的调用示例

url="http://218.242.121.41:8890/itsm/rest/api/itsm/tickets?moduleId=incident&createEndTime=2014-7-30";
String ui = "http://localhost:8890/itsm/rest/api/itsm/tickets?moduleId=incident&createStartTime=2014-7-29&createEndTime=2014-7-30";
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json;charset=utf-8");
System.out.println("response code:" + conn.getResponseCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result;
System.out.println("content:");
result = reader.readLine();
System.out.println(result);

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    httppost和httpget需要的jar包

    在Java编程中,HTTP POST和GET是两种基本的HTTP请求方法,用于客户端向服务器发送数据。为了在Java中实现这些功能,我们需要引入特定的库,这些库通常被打包成JAR(Java Archive)文件。本篇文章将详细讲解HTTP POST...

    org.apache.http.httpentity jar包-系列jar包

    import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; ...

    httpcore-4.3.2.jar和httpmime-4.3.5.jar

    《深入理解HTTPCore与HTTPMIME:构建高效网络通信》 HTTPCore与HTTPMIME是Apache HttpClient库中的核心组件,这两个jar包在Java开发者中有着广泛的应用,尤其在处理HTTP请求和响应时不可或缺。本篇将详细介绍这两个...

    VC通过HttpGet和HttpPost方式与WebService通信,解析返回的Json

    在这个特定的场景中,我们关注的是如何利用VC通过HttpGet和HttpPost方法与WebService进行交互,并处理返回的Json数据。 HttpGet和HttpPost是HTTP协议中的两种主要请求方法。HttpGet是一种无状态、幂等的请求方法,...

    httpcore jar包

    1. **HTTP协议支持**:httpcore提供了对HTTP/1.0和HTTP/1.1协议的支持,包括GET、POST等各种HTTP方法,以及头部处理、状态码解析等。 2. **连接管理**:它包含连接池(Connection Pooling)功能,可以复用HTTP连接...

    org.apache.http包

    import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; ...

    org.apache.http jar包

    org.apache.http jar包 import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org....

    HTTP协议详解及RFC2616(HTTP)中文版

    **HTTP协议详解** HTTP(Hypertext Transfer Protocol)超文本传输协议是互联网上应用最广泛的一种网络协议。它是用于从万维网服务器传输超文本到本地浏览器的传输协议,是Web应用的基础。HTTP协议定义了客户端...

    C++实现HTTP请求

    在IT行业中,网络通信是软件开发的一个重要领域,而HTTP(超文本传输协议)作为互联网上应用最广泛的一种网络协议,被广泛应用于网页浏览、数据传输等场景。本篇文章将详细探讨如何使用C++来实现HTTP的POST和GET请求...

    构建一个简单的HTTP服务器的C#程序实例Ky_HttpServer.rar

    构建一个简单的HTTP服务器的C#程序实例。实现响应GET、POST请求。在服务端创建一个tcp通信来负责监听客户端连接。每次客户端发出请求后,我们根据请问报文来判断客户端的请求类型,然后根据不同的请求类型进行相应的...

    VB做的HTTP简单服务器源码

    标题 "VB做的HTTP简单服务器源码" 描述的是一个使用Visual Basic(VB)编程语言编写的简易HTTP服务器的源代码。这个服务器能够响应HTTP请求,为客户端提供服务,可能是为了教学目的或者作为小型项目的起点。VB是一种...

    vc++HTTP客户端与服务端源代码

    在IT行业中,网络通信是至关重要的一个领域,而HTTP(超文本传输协议)作为网络通信的基础,被广泛应用于Web应用程序的开发。在这个场景下,我们关注的是使用VC++(Microsoft Visual C++)来实现HTTP客户端和服务器...

    图解HTTP,图解HTTP

    ### 图解HTTP:全面解析HTTP协议 #### 一、引言 HTTP协议作为互联网的核心组成部分,对于每一个从事Web开发或维护的技术人员来说都是必须掌握的基础知识。《图解HTTP》一书通过丰富的图表和深入浅出的文字解释,...

    org.apache.http 相关的jar包

    import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import...

    C++编写的Linux下Http请求

    在IT领域,网络编程是不可或缺的一部分,特别是在操作系统如Linux中,开发者经常需要通过HTTP协议进行数据交换。本篇将深入探讨使用C++在Linux环境下实现HTTP请求,包括GET和POST方法。 HTTP(超文本传输协议)是...

    org.apache.http源代码和jar包

    import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org....

    c# http接口设计及调用demo

    在本示例中,我们将关注的是"C# HTTP接口设计及调用demo",这通常涉及到如何创建一个HTTP服务端接口,以及如何使用C#客户端进行调用。HTTP接口在分布式系统中扮演着重要角色,它允许不同组件之间通过HTTP协议交换...

    网络编程HttpServer c++实现

    在本项目中,"网络编程HttpServer c++实现" 是一个使用C++语言编写的HTTP服务器,它允许用户创建和管理基于HTTP协议的服务。HTTP服务器是互联网上的关键组件,它们接收HTTP请求并返回HTTP响应,使得网页和其他资源...

    VC++ HTTP Get Post请求

    在VC++编程环境中,HTTP(超文本传输协议)Get和Post请求是常见的网络通信方法,用于从或向服务器发送数据。这两个方法是Web应用程序与服务器交互的基础,理解它们的工作原理和如何在VC++中实现至关重要。 **HTTP ...

Global site tag (gtag.js) - Google Analytics