关闭

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

764人阅读 评论(0) 收藏 举报
分类:
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表单提交实现。


0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:31020次
    • 积分:600
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:9篇
    • 译文:4篇
    • 评论:17条
    文章分类
    最新评论