httpcomponents-client-4.3.3和jdk1.6 httpserver通过http协议交互数据

服务器端实现HttpHandler处理业务数据

package org.shefron.fc.web.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.util.List;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * 处理HTTP请求并响应
 *
 * @author Administrator
 *
 */
public class BusiHandler implements HttpHandler {

	/**
	 * 处理HTTP请求并响应
	 */
	public void handle(HttpExchange exchange) {
		// if the url "http://x.x.x.x:port/http/req.xml",then the uri is
		// "/http/req.xml"
		URI reqURI = exchange.getRequestURI();
		System.out.println("RequestURI=" + reqURI.toString());

		String method = exchange.getRequestMethod();
		System.out.println("method:"+method);

		String protocol = exchange.getProtocol();
		System.out.println("protocol:"+protocol);

		Headers reqHeaders = exchange.getRequestHeaders();
		System.out.println("requestHeaders:");
		String host = "";
		String reqXmlHead = null;
		for (Entry<String, List<String>> entry: reqHeaders.entrySet()){
			System.out.println("key="+entry.getKey()+",value="+entry.getValue());
			if ("Host".equalsIgnoreCase(entry.getKey())){
				host = entry.getValue().get(0);
			}
			if("xmlHead".equalsIgnoreCase(entry.getKey())){
				reqXmlHead = entry.getValue().get(0);
			}
		}

		if("HTTP/1.1".equals(protocol)){
			protocol = "http";
		}

		System.out.println("------------------------------------");
		System.out.println("URL="+protocol+"://"+host+reqURI);
		System.out.println("xmlhead="+reqXmlHead);

		//处理请求体
//		handleRequestBody(exchange.getRequestBody());
		justPrint(exchange.getRequestBody());

		try {

			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("content-type", "multipart/mixed;charset=utf-8");

			StringBuffer xmlHead = new StringBuffer();
			xmlHead.append("<resinfo>");
			xmlHead.append("<state>true</state>");
			xmlHead.append("</resinfo>");
			String headStr = "<head><content><![CDATA["+xmlHead.toString()+"]]></content></head>";

			responseHeaders.set("xmlhead",headStr);

			OutputStream ut = exchange.getResponseBody();
			OutputStreamWriter writer = new OutputStreamWriter(ut,"UTF-8");

			String xmlStr = "<resinfo><status>正确</status></resinfo>";
			String xmlBody = "xmlbody=<InterBoss><SvcCont><![CDATA["+xmlStr+"]]></SvcCont></InterBoss>";

			exchange.sendResponseHeaders(200, xmlBody.getBytes("UTF-8").length);
			writer.write(xmlBody);

			writer.close();
			ut.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 *
	 * @param input
	 */
	@SuppressWarnings("unused")
	private void handleRequestBody(InputStream input){
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));

			String fieldSepaStr = null;
			while((fieldSepaStr = reader.readLine()) != null){
				handleField(reader, fieldSepaStr);
			}

			input.close();
			reader.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}

	private void handleField(BufferedReader reader,String fieldSepaStr){

		try {
			int lineNumber = 0;
			String lineStr = null;
			String key = null;
			boolean valueFlag = false;
			StringBuffer value = new StringBuffer();
			while((lineStr = reader.readLine()) != null){
				lineNumber++;

				if (lineNumber == 1){
					key = StringUtils.substringAfter(lineStr, "name=\"").replace("\"", "");
					continue;
				}

				if (lineStr.equals(fieldSepaStr)){
					handleField(reader,fieldSepaStr);
					System.out.println("-----------------fieldname="+key);
					System.out.println("-----------------fieldvalue=["+value.toString()+"]");
				}


				if (lineStr.equals(fieldSepaStr+"--")){
					System.out.println("-----------------fieldname="+key);
					System.out.println("-----------------fieldvalue=["+value.toString()+"]");
					break;
				}

				if (StringUtils.isBlank(lineStr) && lineNumber==4){
					valueFlag = true;
					continue;
				}

				if (valueFlag){
					value.append(lineStr+"\n");
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void justPrint(InputStream input){
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));

			String line = null;
			while((line = reader.readLine()) != null){
				System.out.println("line:"+line);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}


	}

}


服务器端启动进程服务:

package org.shefron.fc.web.http;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.HttpServer;

public class StartService {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try{
			HttpServer httpSer = HttpServer.create(new InetSocketAddress(6060), 0);

			httpSer.createContext("/myApp", new BusiHandler() );

			httpSer.setExecutor(Executors.newCachedThreadPool());

			httpSer.start();

		}catch(Exception e){

		}
	}

}


客户端HTTP请求并处理响应:

package org.shefron.fc.web.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class ClientRequest {

	public static void method1(){
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
        	HttpPost httppost =  new HttpPost("http://127.0.0.1:6060/myApp/req.xml");

        	httppost.addHeader("content-type", "multipart/form-data");

    		StringBuffer xmlHead = new StringBuffer();
    		xmlHead.append("<reqinfo>");
    		xmlHead.append("<username>admin</username>");
    		xmlHead.append("<password>admin</password>");
    		xmlHead.append("</reqinfo>");
    		String headStr = "<head><content><![CDATA["+xmlHead.toString()+"]]></content></head>";

    		httppost.addHeader("xmlhead", headStr);

			StringBuffer xmlBody = new StringBuffer();
			String xmlStr = "\n\t<reqinfo>\n\t<status>is it ok ?</status>\n</reqinfo>";
			xmlBody.append("<InterBoss>\n\t<SvcCont><![CDATA["+xmlStr+"]]></SvcCont>\n</InterBoss>");
    		StringBody stringBody = new StringBody(xmlBody.toString(),ContentType.DEFAULT_TEXT.withCharset(Consts.UTF_8));
    		StringBody stringBody2 = new StringBody("It just tests!haha",ContentType.DEFAULT_TEXT.withCharset(Consts.UTF_8));

    		File file = new File("E:\\files\\upload.xml");
    		FileBody fileBody = new FileBody(file,ContentType.APPLICATION_OCTET_STREAM.withCharset(Consts.UTF_8));

    		//传递数据
    		HttpEntity reqEntity = MultipartEntityBuilder.create()
							            .addPart("xmlbody", stringBody)
							            .addPart("test", stringBody2)
							            .addPart("upload.xml", fileBody)
							            .build();
    		httppost.setEntity(reqEntity);

    		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    		nvps.add(new BasicNameValuePair("username", "vip"));
    		nvps.add(new BasicNameValuePair("password", "secret"));

    		//传递参数
    		httppost.setEntity(new UrlEncodedFormEntity(nvps));


    		httppost.setProtocolVersion(HttpVersion.HTTP_1_1);


    		CloseableHttpResponse  response = httpclient.execute(httppost);

			for (Header header :response.getHeaders("xmlhead")){
				System.out.println(header.getName()+":"+header.getValue());
			}



			StatusLine statusLine = response.getStatusLine();
			HttpEntity entity = response.getEntity();

			//Test
//			EntityUtils.consume(entity);

			if (statusLine.getStatusCode() >= 300) {
				throw new HttpResponseException(statusLine
						.getStatusCode(), statusLine
						.getReasonPhrase());
			}
			if (entity == null) {
				throw new ClientProtocolException(
						"Response contains no content");
			}
			try {
				ContentType contentType = ContentType.getOrDefault(entity);

				System.out.println("contentType="+contentType.toString());
				Charset charset = contentType.getCharset();
				if (charset == null) {
					charset = Consts.ISO_8859_1;
				}
				System.out.println("charset:"+charset);

				BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),charset.name()));
				StringBuffer buffer = new StringBuffer();
				String line = null;
				try {
					while((line = reader.readLine()) != null){
						buffer.append(line+"\n");
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}

				System.out.println("xmlbody="+buffer.toString());



			} catch (Exception ex) {
				throw new IllegalStateException(ex);
			} finally{
				response.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		method1();
	}

}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值