Http协议中最基本的四种提交方式的超轻量级简单实现

原创 2013年12月05日 09:36:57
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

public class HttpClientHelper {

	protected static String MIME_JSON = "application/json";
	protected static String MIME_JPEG = "image/jpeg";
	protected static String MIME_BINARY = "binary/octet-stream";
	protected static int connection_timeout = 10 * 1000;
	private static int socket_timeout = 10 * 1000;

	/**
	 * POST 方式提交添加
	 * 
	 * @param url
	 * @param mainString
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPost(String url, String mainString) throws ClientProtocolException, IOException {
		DefaultHttpClient dhc = new DefaultHttpClient();
		HttpPost hp = new HttpPost(url);
		HttpConnectionParams.setConnectionTimeout(hp.getParams(), connection_timeout);
		HttpConnectionParams.setSoTimeout(hp.getParams(), socket_timeout);
		StringEntity strEntity = new StringEntity(mainString);
		strEntity.setContentType(MIME_JSON);
		hp.setEntity(strEntity);
		HttpResponse response = dhc.execute(hp);
		String content = streamTool(response.getEntity().getContent());
		return content;
	}

	/**
	 * POST 方式提交文件
	 * 
	 * @param url
	 * @param mainString
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPostFile(String url, File file) throws ClientProtocolException, IOException {
		DefaultHttpClient dhc = new DefaultHttpClient();
		HttpPost hp = new HttpPost(url);
		HttpConnectionParams.setConnectionTimeout(hp.getParams(), connection_timeout);
		HttpConnectionParams.setSoTimeout(hp.getParams(), socket_timeout);
		FileEntity fileEntity = new FileEntity(file, MIME_JPEG);
		hp.setEntity(fileEntity);
		HttpResponse response = dhc.execute(hp);
		String content = streamTool(response.getEntity().getContent());
		return content;
	}

	/**
	 * PUT 方式提交修改数据
	 * 
	 * @param url
	 * @param mainString
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPut(String url, String mainString) throws ClientProtocolException, IOException {
		DefaultHttpClient dhc = new DefaultHttpClient();
		HttpPut hp = new HttpPut(url);
		HttpConnectionParams.setConnectionTimeout(hp.getParams(), connection_timeout);
		StringEntity strEntity = new StringEntity(mainString);
		strEntity.setContentType(MIME_JSON);
		hp.setEntity(strEntity);
		HttpResponse response = dhc.execute(hp);
		String content = streamTool(response.getEntity().getContent());
		return content;
	}

	/**
	 * DELETE 方式提交url
	 * 
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doDelete(String url) throws ClientProtocolException, IOException {
		DefaultHttpClient dhc = new DefaultHttpClient();
		HttpDelete hp = new HttpDelete(url);
		HttpConnectionParams.setConnectionTimeout(hp.getParams(), connection_timeout);
		HttpConnectionParams.setSoTimeout(hp.getParams(), socket_timeout);
		HttpResponse response = dhc.execute(hp);
		return null;
		// if (response.getEntity().getContent() != null) {
		// return streamTool(response.getEntity().getContent());
		// } else {
		// return null;
		// }

	}

	/**
	 * GET 方式查询url
	 * 
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doGet(String url) throws ClientProtocolException, IOException {
		DefaultHttpClient dhc = new DefaultHttpClient();
		HttpGet hp = new HttpGet(url);
		HttpConnectionParams.setConnectionTimeout(hp.getParams(), connection_timeout);
		HttpConnectionParams.setSoTimeout(hp.getParams(), socket_timeout);
		HttpResponse response = dhc.execute(hp);
		String content = streamTool(response.getEntity().getContent());
		return content;
	}

	public static String streamTool(InputStream is) throws IOException {
		StringBuffer sb;
		sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		String tmp;
		while ((tmp = br.readLine()) != null) {
			sb.append(tmp);
			sb.append("\n");
		}
		return sb.toString();
	}
}

这个例子很简单,这是以前项目当中自己写的一个小例子,用于在http请求的body部分提交任意字符串,而不是传统的键值对提交方式。

当时服务器端使用了Odata协议,而客户端没有一个OData的协议实现,于是我就自己实现了一下。具体上层实现没有贴出来,因为代码

搬运的时候遗失了。

上面的http实现用的是apache的包里面的类实现,下面贴出来用java.net包实现的http协议。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http辅助类,包含put/get/post/delete方法,不传参数
 * 
 * @author Liang
 * 
 */
public class HttpNetHelper {
	/**
	 * POST方式提交添加
	 * 
	 * @param mainurl
	 * @param jsonString
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String doPost(String mainurl, String jsonString) throws Exception {
		return common(mainurl, jsonString, "POST");
	}

	/**
	 * PUT方式提交修改数据
	 * 
	 * @param mainurl
	 * @param jsonString
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String doPut(String mainurl, String jsonString) throws Exception {
		return common(mainurl, jsonString, "PUT");
	}

	/**
	 * GET方式查询url
	 * 
	 * @param mainurl
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String doGet(String mainurl) throws Exception {
		return common(mainurl, null, "GET");
	};

	/**
	 * DELETE 方式提交url
	 * 
	 * @param mainurl
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String doDelete(String mainurl) throws Exception {
		return common(mainurl, null, "DELETE");
	}

	/**
	 * http请求公用部分
	 * 
	 * @param mainurl
	 * @param jsonString
	 * @param method
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	private static String common(String mainurl, String jsonString, String method) throws UnsupportedEncodingException, IOException {

		URL url = new URL(mainurl);
		HttpURLConnection hc = (HttpURLConnection) url.openConnection();
		hc.setRequestMethod(method);
		hc.setDoInput(true);
		hc.setDoOutput(true);
		hc.setConnectTimeout(8000);
		hc.setUseCaches(false);
		hc.setRequestProperty("Content-Type", "application/json");

		if (jsonString != null) {
			OutputStreamWriter osw = new OutputStreamWriter(hc.getOutputStream(), "UTF-8");
			osw.write(jsonString);
			osw.flush();
			osw.close();
		}
		if (hc.getResponseCode() == 200) {
			return streamTool(hc.getInputStream());
		} else {
			return String.valueOf(hc.getResponseCode());
		}

	}

	private static String streamTool(InputStream is) throws IOException {
		StringBuffer sb;
		sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		String tmp;
		while ((tmp = br.readLine()) != null) {
			sb.append(tmp);
			sb.append("\n");
		}
		return sb.toString();
	}
}


以后我会慢慢贴出来具体的http协议键值对提交,post表单提交实现。


相关文章推荐

第三学 linux内核中最基本的数据组织方式——list.h分析(1)

如果说内核态helloworid是我们进入linux内核世界的第一步,那么双链表操作算是我们学习linux内核数据组织方式的敲门砖。               在这里,我们首先要搞清一个概念,我们...
  • bcs_01
  • bcs_01
  • 2013年05月06日 21:22
  • 579

第四学 linux内核中最基本的数据组织方式——list.h分析(2)

7、遍历节点操作         这节我们介绍双连表的遍历。遍历是一个非常重要的概念,学过STL的童鞋们都知道,C++的容器的大量的算法都是建立在遍历这个概念基础之上的,比如查找元素,元素排序,等等...
  • bcs_01
  • bcs_01
  • 2013年05月07日 11:29
  • 602

基于HTTP协议的轻量级开源简单队列服务:HTTPSQS[原创]

基于HTTP协议的轻量级开源简单队列服务:HTTPSQS[原创] 大 | 中 | 小 [ 2009-12-30 07:01 | by张宴 ]   [文章作者:张宴 本文版本:v1.7.1 最...
  • samxx8
  • samxx8
  • 2011年11月05日 23:34
  • 468

基于HTTP协议的轻量级开源简单队列服务:HTTPSQS[张宴]

[ 2009-12-30 07:01 | by 张宴 ]   [文章作者:张宴 本文版本:v1.6.0 最后修改:2011.04.21 转载请注明原文链接...
  • wzm112
  • wzm112
  • 2011年05月17日 18:25
  • 1058

基于HTTP协议的轻量级开源简单队列服务:HTTPSQS

转自点击打开链接 HTTPSQS(HTTP Simple Queue Service)是一款基于 HTTP GET/POST 协议的轻量级开源简单消息队列服务,使用 Tokyo Cabinet 的 ...

基于HTTP协议的轻量级开源简单队列服务:HTTPSQS(2009)

[ 2009-12-30 07:01 | by 张宴 ]   [文章作者:张宴 本文版本:v1.7.1 最后修改:2011.11.04 转载请注明原文链接:http://blog.zyan.cc/...

基于HTTP协议的轻量级开源简单队列服务

[文章作者:张宴 本文版本:v1.7.1 最后修改:2011.11.04 转载请注明原文链接:http://blog.s135.com/httpsqs/]   HTTPSQS(HTTP Simple...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Http协议中最基本的四种提交方式的超轻量级简单实现
举报原因:
原因补充:

(最多只允许输入30个字)