ac91ff9132a5d3318605163885625265a630c597.svn-base 12.9 KB
package com.phxl.common.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


 
public class HttpUtils {




	public static String readContentFromGet(String url) throws IOException {
		// 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
		URL getUrl = new URL(url);
		// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
		// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.addRequestProperty("Content-Type","application/xml");
		// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
		// 服务器
		connection.connect();
		// 取得输入流,并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
		String lines;
		// while ((lines = reader.readLine()) != null){
		// //lines = new String(lines.getBytes(), "utf-8");
		// System.out.println(lines);
		// }
		lines = reader.readLine();
		reader.close();
		// 断开连接
		connection.disconnect();

		return lines;
	}

	public static String readContentFromPost2(String url, String content) throws IOException {
		// Post请求的url,与get不同的是不需要带参数
		URL postUrl = new URL(url);
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// Output to the connection. Default is
		// false, set to true because post
		// method must write something to the
		// connection
		// 设置是否向connection输出,因为这个是post请求,参数要放在
		// http正文内,因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// Set the post method. Default is GET
		connection.setRequestMethod("POST");
		// Post cannot use caches
		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		// This method takes effects to
		// every instances of this class.
		// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
		// connection.setFollowRedirects(true);

		// This methods only
		// takes effacts to this
		// instance.
		// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
		connection.setInstanceFollowRedirects(true);
		// Set the content type to urlencoded,
		// because we will write
		// some URL-encoded content to the
		// connection. Settings above must be set before connect!
		// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		//connection.addRequestProperty("Content-Type","application/xml");
		//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		/* 设置头的信息 */

		connection.setRequestProperty("Content-Type", "text/xml");


		// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致,content

		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
		out.writeBytes(content);
		out.flush();
		out.close(); // flush and close
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
		String line = "";
		// while ((line = reader.readLine()) != null){
		// //line = new String(line.getBytes(), "utf-8");
		// System.out.println(line);
		// }
		line = reader.readLine();
		reader.close();
		connection.disconnect();

		return line;
	}

	public static String readContentFromPost(String url, String content) throws IOException {
		// Post请求的url,与get不同的是不需要带参数
		URL postUrl = new URL(url);
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// Output to the connection. Default is
		// false, set to true because post
		// method must write something to the
		// connection
		// 设置是否向connection输出,因为这个是post请求,参数要放在
		// http正文内,因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// Set the post method. Default is GET
		connection.setRequestMethod("POST");
		// Post cannot use caches
		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		// This method takes effects to
		// every instances of this class.
		// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
		// connection.setFollowRedirects(true);

		// This methods only
		// takes effacts to this
		// instance.
		// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
		connection.setInstanceFollowRedirects(true);
		// Set the content type to urlencoded,
		// because we will write
		// some URL-encoded content to the
		// connection. Settings above must be set before connect!
		// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		//connection.addRequestProperty("Content-Type","application/xml");
		//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		/* 设置头的信息 */

		connection.setRequestProperty("Content-Type", "application/xml");


		// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致,content

		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
		out.writeBytes(content);
		out.flush();
		out.close(); // flush and close
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
		String line = "";
		// while ((line = reader.readLine()) != null){
		// //line = new String(line.getBytes(), "utf-8");
		// System.out.println(line);
		// }
		line = reader.readLine();
		reader.close();
		connection.disconnect();

		return line;
	}

	public static String readContentFromPost(String url, String content, String contentType) throws IOException {
		// Post请求的url,与get不同的是不需要带参数
		URL postUrl = new URL(url);
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		// Output to the connection. Default is
		// false, set to true because post
		// method must write something to the
		// connection
		// 设置是否向connection输出,因为这个是post请求,参数要放在
		// http正文内,因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// Set the post method. Default is GET
		connection.setRequestMethod("POST");
		// Post cannot use caches
		// Post 请求不能使用缓存
		connection.setUseCaches(false);

		// This method takes effects to
		// every instances of this class.
		// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
		// connection.setFollowRedirects(true);

		// This methods only
		// takes effacts to this
		// instance.
		// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
		connection.setInstanceFollowRedirects(true);
		// Set the content type to urlencoded,
		// because we will write
		// some URL-encoded content to the
		// connection. Settings above must be set before connect!
		// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		//connection.addRequestProperty("Content-Type","application/xml");
		//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		/* 设置头的信息 */

		connection.setRequestProperty("Content-Type", contentType);


		// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致,content

		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
		out.writeBytes(content);
		out.flush();
		out.close(); // flush and close
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
		String line = "";
		// while ((line = reader.readLine()) != null){
		// //line = new String(line.getBytes(), "utf-8");
		// System.out.println(line);
		// }
		line = reader.readLine();
		reader.close();
		connection.disconnect();

		return line;
	}

	public static  void fff(String url,String xml) {

		try{
			URL postUrl = new URL(url);
			// 建立http连接
			HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
			// 设置允许输出
			conn.setDoOutput(true);

			conn.setDoInput(true);

			// 设置不用缓存
			conn.setUseCaches(false);
			// 设置传递方式
			conn.setRequestMethod("POST");
			// 设置维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置文件字符集:
			conn.setRequestProperty("Charset", "UTF-8");
			//转换为字节数组
			byte[] data = xml.getBytes();
			// 设置文件长度
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			// 设置文件类型:
			conn.setRequestProperty("contentType", "applicaiton/xml");

			// 设置文件类型:
			//conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
			// 设置接收类型否则返回415错误
			//conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
			conn.setRequestProperty("accept","application/xml");
			// 开始连接请求
			conn.connect();
			OutputStream out = conn.getOutputStream();
			// 写入请求的字符串
			out.write(data);
			out.flush();
			out.close();

			System.out.println(conn.getResponseCode());
		}catch (Exception e){
			System.out.println(e);
		}

	}

	public static void main(String[] args) {

		// String content="<p>测试测试测试测试测试测试测试测试测试测试测试测试</p>";
		//String mytext = "act=2005&type=1&limit=30&loginUserId=&start=0&keyword=";
		String mytext = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><book><id>1</id><name>王森勇</name><author>tiger</author></book>";
		/*
		 * try { //mytext = "content="+content+
		 * "&custId=0c8469cc950f44ca8728a2ec97db1222&sourceId=1&sourceType=1";
		 * //mytext = "content="+java.net.URLEncoder.encode(content, "utf-8")+
		 * "&custId=0c8469cc950f44ca8728a2ec97db1222&sourceId=1&sourceType=1";
		 * //System.out.println(mytext); //String mytext2 =
		 * java.net.URLDecoder.decode(mytext, "utf-8");
		 * //System.out.println(mytext2); } catch (UnsupportedEncodingException
		 * e) { // TODO Auto-generated catch block e.printStackTrace(); }
		 */
		try {
/*			String url = "http://localhost:8080/upload/spd/getxml";
			String line = HttpUtils.readContentFromGet(url);
			System.out.println(line);*/


			String url = "http://localhost:8080/medicinal-supplier/bookInfo/sendxml";
			//HttpUtils.initHeaderParam();
			//fff(url,mytext);
			String line = HttpUtils.readContentFromPost(url, mytext);
			System.out.println(line);
			Map<String, Object> aaa = JsonUtils.fromJson(line, Map.class);

			/*
			 * for (Map.Entry<String, Object> entry : aaa.entrySet()) {
			 * if(entry.getValue() instanceof ArrayList ){
			 * aaa.put(entry.getKey(), (List)entry.getValue()); } }
			 * 
			 * bbb = aaa.get("data");
			 */
			// System.out.println(bbb instanceof ArrayList);

			// List ccc =(List)bbb;
			/* System.out.println(bbb); */
			// Object ddd = ccc.get(0);
			// System.out.println(ccc.get(0).get("clubId"));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}