⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httphelper.java

📁 采用JAVA开发
💻 JAVA
字号:
/*
 * Created on 2004-8-10
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package com.gctech.misc.util;
import java.util.*;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
//import javax.microedition.io.Connector;
//import javax.microedition.io.HttpConnection;
import java.net.*;
public class HttpHelper {
	private static final int MAX_REDIRECTS = 5;
	private static final int MAX_READ_SIZE = 2000; //允许从server端读取2000个
	public HttpHelper() {
	}
	private String getResponse(InputStream in) {
		try {
			byte[] buf = new byte[MAX_READ_SIZE];
			StringBuffer sb = new StringBuffer();
			String temp = null;
			while (true) {
				int count = in.read(buf, 0, MAX_READ_SIZE);
				if (count != -1) {
					temp = new String(buf, 0, count);
					sb.append(temp);
				} else {
					break;
				}

			}

			return sb.toString();

		} catch (Exception ex) {
			throw new IllegalStateException(ex.getMessage());
		}

	}

	private Hashtable toMap(String response) {
		int start = 0;
		int end = 0;
		String line = null;
		int lineIndex = 0;
		String key = null;
		String value = null;
		Hashtable t = new Hashtable();
		while ((end = response.indexOf("\r\n", start)) != -1) {
			line = response.substring(start, end);
			start = end + 2;
			if (start > response.length())
				break;
			lineIndex = line.indexOf("=", 0);
			key = line.substring(0, lineIndex);
			value = line.substring(lineIndex + 1);
			t.put(key, value);
		}
		return t;
	}

	private String makeQuery(Hashtable map) {
		StringBuffer sb = new StringBuffer();
		for (Enumeration e = map.keys(); e.hasMoreElements();) {
			String key = e.nextElement().toString();
			sb.append(key).append("=").append(map.get(key).toString()).append("&");
		}
		sb.setLength(sb.length() - 1);
		//sb.append("\r\n"); 是否需要增加
		return sb.toString(); //must encode;
	}

	public Hashtable postMapResponse(String url, Hashtable parameters) {
		return toMap(postStringResponse(url, parameters));
	}

	public String postStringResponse(String url, Hashtable map) {
		return this.postStringResponse(url, this.makeQuery(map));
	}

	public String postStringResponse(String url, String query) {
		InputStream is = null;
		OutputStream os = null;
		HttpURLConnection conn = null;
		int redirects = 0;
		try {

			//		String query = makeQuery(parameters);//"index=books&field-keywords=" + isbn + "\r\n" ;
			String requestMethod = "POST";

			while (redirects < MAX_REDIRECTS) {
				System.out.println("ready connect");

				conn = (HttpURLConnection) new URL(url).openConnection();
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setRequestMethod(requestMethod);

				System.out.println("connect ok");

				conn.setRequestMethod(requestMethod);
				conn.setRequestProperty("Connection", "Close");
				if (requestMethod.equals(requestMethod)) {
					conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
					os = conn.getOutputStream();
					os.write(query.getBytes());
					os.close();
					os = null;
				}

				// Read the response from the server
				is = conn.getInputStream();
				int code = conn.getResponseCode();

				// If we get a redirect, try again at the new location
				if ((code >= HttpURLConnection.HTTP_MOVED_PERM && code <= HttpURLConnection.HTTP_SEE_OTHER)
					|| code == HttpURLConnection.HTTP_MOVED_TEMP) //??
					{
					// Get the URL of the new location (always absolute)
					url = conn.getHeaderField("Location");
					is.close();
					conn.disconnect();
					is = null;
					conn = null;

					if (++redirects > MAX_REDIRECTS) {
						// Too many redirects - give up.

						break;
					}

					// Choose the appropriate request method
					requestMethod = "POST";
					if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_SEE_OTHER) {
						requestMethod = "GET";
					}
					continue;
				}
				//		  String type = conn.getType () ;
				String type = "text/html";
				System.out.println("response type " + type);
				if (code == HttpURLConnection.HTTP_OK && type.indexOf("text/html") != -1) {
					System.out.println("retrive date from connection");
					return this.getResponse(is);
				} else {
					throw new IllegalStateException("response error");
				}
			}

			throw new IllegalStateException("can not find the url");
		} catch (Throwable t) {
			System.out.println(t);
			throw new IllegalStateException(t.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ex) {
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException ex) {
				}
			}
			if (conn != null) {
				try {
					conn.disconnect();
				} catch (Exception ex) {
				}
			}
		}

	}

	public static void main(String[] args) {
		HttpHelper h = new HttpHelper();
		Hashtable t = new Hashtable();
		String url = "http://localhost/misc/TestEnv";
		//	  t.put("tid","78");
		System.out.println(h.postStringResponse(url, "<?xml version=\""
				+ "1.0\""
				+ " encoding=\""
				+ "UTF-8\""
				+ "?><soap:Envelope xmlns:soap=\""
				+ "http://schemas.xmlsoap.org/soap/envelope/\""
				+ " xmlns:xsd=\""
				+ "http://www.w3.org/2001/XMLSchema\""
				+ " xmlns:xsi=\""
				+ "http://www.w3.org/2001/XMLSchema-instance\""
				+ " xmlns:SOAP-ENC=\""
				+ "http://schemas.xmlsoap.org/soap/encoding/\""
				+ "><soap:Header><TransactionID xmlns=\""
				+ "01000000000http://www.monternet.com/dsmp/schemas/\""
				+ ">01000000000</TransactionID></soap:Header><soap:Body><SyncOrderRelationResp xmlns=\""
				+ "http://www.monternet.com/dsmp/schemas/\""
				+ "><Version>1.5.0</Version><MsgType>SyncOrderRelationReq</MsgType><hRet>0</hRet></SyncOrderRelationResp></soap:Body></soap:Envelope>"));
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -