http

来源:互联网 发布:阿里云自动测试代码 编辑:程序博客网 时间:2024/06/05 23:54
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);

0 0
原创粉丝点击