Java发送http请求工具类()

模拟get方法发送请求代码:

public static String doGet(String link, String charset) {
		HttpURLConnection conn = null;
		try {
			URL url = new URL(link);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			for (int i = 0; (i = in.read(buf)) > 0;) {
				out.write(buf, 0, i);
			}
			out.flush();
			String s = new String(out.toByteArray(), charset);
			return s;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}

	/**
	 * UTF-8编码
	 * 
	 * @param link
	 * @return
	 */
	public static String doGet(String link) {
		return doGet(link, "UTF-8");
	}

使用post传输表单数据:

这个类将map<String,string>数组的内容转化成post表单传输的路径:

public static String generatorParamString(Map<String, String> parameters) {
		StringBuffer params = new StringBuffer();
		if (parameters != null) {
			for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
				String name = iter.next();
				String value = parameters.get(name);
				params.append(name + "=");
				try {
					params.append(URLEncoder.encode(value, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e.getMessage(), e);
				} catch (Exception e) {
					String message = String.format("'%s'='%s'", name, value);
					throw new RuntimeException(message, e);
				}
				if (iter.hasNext())
					params.append("&");
			}
		}
		return params.toString();
	}
发送post请求:

public static String doPost(String reqUrl, Map<String, String> parameters) {
		HttpURLConnection urlConn = null;
		try {
			urlConn = sendPost(reqUrl, parameters);
			String responseContent = getContent(urlConn);
			return responseContent.trim();
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
				urlConn = null;
			}
		}
	}
private static HttpURLConnection sendPost(String reqUrl, Map<String, String> parameters) {
		HttpURLConnection urlConn = null;
		try {

			String params = generatorParamString(parameters);
			URL url = new URL(reqUrl);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setConnectTimeout(5000);// (单位:毫秒)jdk
			urlConn.setReadTimeout(5000);// (单位:毫秒)jdk 1.5换成这个,读操作超时
			urlConn.setDoOutput(true);
			byte[] b = params.getBytes("UTF-8");
			urlConn.getOutputStream().write(b, 0, b.length);
			urlConn.getOutputStream().flush();
			urlConn.getOutputStream().close();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return urlConn;
	}


获取响应内容:

private static String getContent(HttpURLConnection urlConn) {
		try {
			String responseContent = null;
			InputStream in = null;
			if (urlConn.getResponseCode() == 200) {
				in = urlConn.getInputStream();
			} else {
				in = urlConn.getErrorStream();
			}
			BufferedReader rd = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String tempLine = rd.readLine();
			StringBuffer tempStr = new StringBuffer();
			String crlf = System.getProperty("line.separator");
			while (tempLine != null) {
				tempStr.append(tempLine);
				tempStr.append(crlf);
				tempLine = rd.readLine();
			}
			responseContent = tempStr.toString();
			rd.close();
			in.close();
			return responseContent;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

发送put请求来传输二进制文件:

将两个字节数组整合一起

public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){  
	        byte[] byte_3 = new byte[byte_1.length+byte_2.length];  
	        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);  
	        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);  
	        return byte_3;  
	    }  
发送请求:

public static String doPut(String reqUrl,byte[]data,String ID) {
		HttpURLConnection urlConn = null;
		try {
			urlConn = sendPut(reqUrl,data, ID);
			String responseContent = getContent(urlConn);
			return responseContent.trim();
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
				urlConn = null;
			}
		}
	}
	
	public static HttpURLConnection sendPut(String reqUrl,byte[]data,String ID) {
		HttpURLConnection urlConn = null;
		String path = reqUrl.concat("/").concat(ID);
		try {
			URL url = new URL(path);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setDoInput(true);  
			urlConn.setDoOutput(true);  
			urlConn.setRequestMethod("PUT");  
	        OutputStream urlOutputStream = urlConn.getOutputStream();  
	        urlOutputStream.write(data);
	        urlConn.getOutputStream().flush();
	        urlOutputStream.close();  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e.getMessage(), e);
			
		}
		return urlConn;
	}

使用post传输二进制文件:

public static String doFilePost(String reqUrl,String name,byte[] data) {
		HttpURLConnection urlConn = null;
		try {
			urlConn = sendFilePost(reqUrl,name, data);
			String responseContent = getContent(urlConn);
			return responseContent.trim();
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
				urlConn = null;
			}
		}
	}
	
	public static HttpURLConnection sendFilePost(String reqUrl,String name,byte[] data) {
		HttpURLConnection urlConn = null;
		try {


			String params = name + "=";
			URL url = new URL(reqUrl);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setConnectTimeout(5000);// (单位:毫秒)jdk
			urlConn.setReadTimeout(5000);// (单位:毫秒)jdk 1.5换成这个,读操作超时
			urlConn.setDoOutput(true);
			byte[] b = params.getBytes("UTF-8");
			byte[] sum = byteMerger(b, data);
			urlConn.getOutputStream().write(sum, 0, sum.length);
			urlConn.getOutputStream().flush();
			urlConn.getOutputStream().close();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return urlConn;
	}

获取http response写入的文件:

public static byte[] doFileGet (String link) {
		HttpURLConnection conn = null;
		byte[] result = null;
		try {
			URL url = new URL(link);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			for (int i = 0;(i = in.read(buf)) > 0 ;) {
				out.write(buf, 0, i);
			}
			out.flush();
			result = out.toByteArray();
			return result;
		} catch (Exception e) {
			return null;
		}finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值