欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在java中http的get和post请求

程序员文章站 2022-05-09 10:28:11
...
一个比较简单的工具类,不多解释了,直接上代码
package com.sharebo.util;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
/**
 * http转发工具类
 * @author 郭鹏飞
 *
 */
public class HttpUtil {
	
	/**
	 * http get请求
	 * <blockquote><pre>
	 * 返回数据拼装为String类型<p>
	 * 如果需要返回其他类型的数据,请另写方法改动
	 * </pre></blockquote>
	 * @param httpUrl
	 * @return
	 */
	public static String request_get(String httpUrl) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	        
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setConnectTimeout(5000);
	        connection.setReadTimeout(20000);
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        //e.printStackTrace();
	    }
	    return result;
	}
	
	/**
	 * http post请求
	 * @param httpUrl
	 * @param httpArg
	 * @return
	 */
	public static String request_post(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	        
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setConnectTimeout(5000);
	        connection.setReadTimeout(20000);
	        connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
}