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表单提交实现。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值