Http协议中最基本的四种提交方式的超轻量级简单实现
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表单提交实现。


阅读更多
个人分类: java android
想对作者说点什么? 我来说一句

LiteServe2.7中文注册版

2009年03月01日 892KB 下载

ibaties自动生成代码

2014年04月16日 3.73MB 下载

caddy_linux_amd64

2017年11月16日 4.77MB 下载

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭