关于虚拟服务器接收问题

[color=red]通过executeMethod方法打开服务器对应的方法,相当于往某地方送信[/color]
本文参考:
[url]http://blog.sina.com.cn/s/blog_9ed7f0d70101i8op.html[/url]
[url]http://www.cnblogs.com/cnryb/archive/2013/06/27/3158027.html[/url]

HttpClient httpClient = new HttpClient(); //打开窗口
PostMethod getMethod = new PostMethod("http://localhost:8080/webapp/"); //输入网址
try {
int statusCode = httpClient.executeMethod(getMethod); //按下回车运行,得到返回码
System.out.println(statusCode);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + getMethod.getStatusLine());
}
//读取内容
byte[] responseBody = getMethod.getResponseBody(); //得到返回的内容
//处理内容
System.out.println(new String(responseBody));
} catch (Exception e) {
e.printStackTrace();
} finally {
getMethod.releaseConnection();
}

[color=red]下面代码模仿服务器,通过代码,构建"http://localhost:8080/webapp/"的服务器,接收内容,executeMethod 会调用handle方法[/color]

package com.cnryb;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import org.apache.http.HttpStatus;

import com.sun.net.httpserver.*;

public class HttpSer {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// HttpServer server = HttpServer.create(new InetSocketAddress(
// "127.0.0.1", 8765), 0);
// server.createContext("/",new MyResponseHandler());
// server.setExecutor(null); // creates a default executor
// server.start();
[align=center]
ExecutorService executor = Executors.newFixedThreadPool(20);
int port = Integer.parseInt(prop.getProperty("service_port"));// 8080
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
String url = prop.getProperty("service_url");//wapp
HttpContext context = server.createContext(url, new MyResponseHandler ());
context.getFilters().add(new ParameterFilter());
server.setExecutor(executor);
server.start();[/align]

}
public static class MyResponseHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
// 可以获取相应的内容 以下自己追加
Map<String, Object> params = (Map<String, Object>)httpExchange.getAttribute("parameters");
if (params.get("xml") != null) {
resquestBody = params.get("xml").toString();
} else if (params.get("text/xml") != null) {
resquestBody = params.get("text/xml").toString();
} else if (params.get("OriginRequestBody") != null) {
resquestBody = params.get("OriginRequestBody").toString();
}
// -------------------------------------


//针对请求的处理部分
//返回请求响应时,遵循HTTP协议
String responseString = "<font color='#ff0000'>Hello! This a HttpServer!</font>";
//设置响应头
httpExchange.sendResponseHeaders(HttpStatus.SC_OK, responseString.length());
OutputStream os = httpExchange.getResponseBody();
os.write(responseString.getBytes());
os.close();
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值