Http请求方式汇总

一、HttpClient发送请求

       导入apache的httpclient  jar包

        1.1通过CloseableHttpClient发送xml格式参数的post请求

/**
	 * 通过CloseableHttpClient发送xml格式参数的post请求
	 * @param url
	 * @param xmlString
	 * @return
	 */
	public static String sendXmlPost(String url,String xmlString){
		//1.创建httpclient工具对象
		CloseableHttpClient client = HttpClients.createDefault();
		//2.创建post请求方法
		HttpPost post = new HttpPost(url);
		 // 构建请求配置信息(可选)
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
                .setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
                .setSocketTimeout(10 * 1000) // 数据传输的最长时间
                .build();
        post.setConfig(config);
        
		CloseableHttpResponse response = null;
		String resultMsg = null;
        try{
        	//设置请求头部类型
        	post.setHeader("Content-Type","text/xml;charset=UTF-8");
        	//设置请求体
        	StringEntity xmlEntity = new StringEntity(xmlString,Consts.UTF_8);
        	post.setEntity(xmlEntity);
        	//执行
        	response = client.execute(post);
        	//如果只有状态码返回,设置返回数据为状态码
        	if(response.getStatusLine().getStatusCode() == 200){
        		resultMsg = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        	return resultMsg;
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	try {
        		if(client!=null){
                    client.close();
                }
                if(response != null){
                	response.close();
                }
        	}catch (IOException e) {
                e.printStackTrace();
            }
        }
       
		return null;
	}

        1.2发送json格式字符串的请求

/**
	 * 发送json格式字符串的请求
	 * @param url
	 * @param json
	 * @return
	 */
	public static String sendJsonPost(String url,String json){
		//1.创建httpclient工具对象
		CloseableHttpClient client = HttpClients.createDefault();
		//2.创建post请求方法
		HttpPost post = new HttpPost(url);
		CloseableHttpResponse response = null;
		String resultMsg = null;
        try{
        	//设置请求头部类型
        	post.setHeader("Content-Type","application/json;charset=UTF-8");
        	//设置请求体
        	StringEntity jsonEntity = new StringEntity(json,Consts.UTF_8);
        	post.setEntity(jsonEntity);
        	//执行
        	response = client.execute(post);
        	//如果只有状态码返回,设置返回数据为状态码
        	if(response.getStatusLine().getStatusCode() == 200){
        		resultMsg = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        	return resultMsg;
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	try {
        		if(client!=null){
                    client.close();
                }
                if(response != null){
                	response.close();
                }
        	}catch (IOException e) {
                e.printStackTrace();
            }
        }
       
		return null;
	}

         1.3通过httpclient模拟表单发送请求

/**
	 * 通过httpclient模拟表单发送请求
	 * @param url
	 * @param map
	 * @return
	 */
	public static String sendFormPost(String url,Map<String,String> map){
		//1.创建httpclient工具对象
		CloseableHttpClient client = HttpClients.createDefault();
		//2.创建post请求方法
		HttpPost post = new HttpPost(url);
		
		//封装参数
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		for(Map.Entry<String, String> entry:map.entrySet()){
			parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
		}
		// 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,Consts.UTF_8);
		
		CloseableHttpResponse response = null;
		String resultMsg = null;
        try{
        	//设置请求头部类型
        	post.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        	//设置请求体
        	post.setEntity(formEntity);
        	//执行
        	response = client.execute(post);
        	//如果只有状态码返回,设置返回数据为状态码
        	if(response.getStatusLine().getStatusCode() == 200){
        		resultMsg = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        	return resultMsg;
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	try {
        		if(client!=null){
                    client.close();
                }
                if(response != null){
                	response.close();
                }
        	}catch (IOException e) {
                e.printStackTrace();
            }
        }
       
		return null;
	}

         1.4通过httpclient模拟表单发送请求

public static String sendGet() throws URISyntaxException{
		//1.创建httpclient工具对象
		CloseableHttpClient client = HttpClients.createDefault();
		
		HttpGet get = new HttpGet(new URIBuilder("http://localhost:8080/xxxxxx/get").setParameter("wd", "java").build());
		CloseableHttpResponse response = null;
		String resultMsg = null;
        try {
            // 执行请求
            response = client.execute(get);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            return resultMsg;
        }catch(Exception e){
        	e.printStackTrace();
        }finally {
        	try {
        		if(client!=null){
                    client.close();
                }
                if(response != null){
                	response.close();
                }
			} catch (IOException e) {
				e.printStackTrace();
			}
            
        }
		return null;
	}

二、java内置的URL工具类发送请求

       2.1java的URL发送JSON数据请求

public static String sendPost(String url, String param) {
	    OutputStreamWriter out = null;
	    BufferedReader in = null;
	    String result = "";
	
	    try {
	        URL realUrl = new URL(url);
	        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
	
	        // 发送POST请求必须设置如下两行
	        conn.setDoOutput(true);// 向连接中写入数据
	        conn.setDoInput(true);// 从连接中读取数据
	        
	        //conn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
	        conn.setUseCaches(false);//Post请求不能使用缓存
	        // 设置请求方式为POST方法
	        conn.setRequestMethod("POST");    
	
	        // 设置通用的请求属性
	        conn.setRequestProperty("accept", "*/*");
	        conn.setRequestProperty("connection", "Keep-Alive");
	        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
	        conn.connect();
	
	        // 获取URLConnection对象对应的输出流
	        out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
	        // 发送请求参数,发送的数据在此处发送。
	        out.write(param);
	        // flush输出流的缓冲
	        out.flush();
	        // 定义BufferedReader输入流来读取URL的响应
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
	        String line ;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	    } catch (Exception e) {
	        System.out.println("发送 POST 请求出现异常!"+e);
	        e.printStackTrace();
	    }
	    //使用finally块来关闭输出流、输入流
	    finally{
	        try{
	            if(out!=null){
	                out.close();
	            }
	            if(in!=null){
	                in.close();
	            }
	        }
	        catch(IOException ex){
	            ex.printStackTrace();
	        }
	    }
	    return result;
	}

      2.2java的URL发送xml数据请求

//java的URL发送xml数据请求
	public static String sendXml(String url, String param) {
	    OutputStreamWriter out = null;
	    BufferedReader in = null;
	    String result = "";
	
	    try {
	        URL realUrl = new URL(url);
	        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
	
	        // 发送POST请求必须设置如下两行
	        conn.setDoOutput(true);// 向连接中写入数据
	        conn.setDoInput(true);// 从连接中读取数据
	        
	        //conn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
	        conn.setUseCaches(false);//Post请求不能使用缓存
	        // 设置请求方式为POST方法
	        conn.setRequestMethod("POST");    
	
	        // 设置通用的请求属性
	        conn.setRequestProperty("accept", "*/*");
	        conn.setRequestProperty("connection", "Keep-Alive");
	        conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
	        conn.connect();
	
	        // 获取URLConnection对象对应的输出流
	        out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
	        // 发送请求参数,发送的数据在此处发送。
	        out.write(param);
	        // flush输出流的缓冲
	        out.flush();
	        // 定义BufferedReader输入流来读取URL的响应
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
	        String line ;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	    } catch (Exception e) {
	        System.out.println("发送 POST 请求出现异常!"+e);
	        e.printStackTrace();
	    }
	    //使用finally块来关闭输出流、输入流
	    finally{
	        try{
	            if(out!=null){
	                out.close();
	            }
	            if(in!=null){
	                in.close();
	            }
	        }
	        catch(IOException ex){
	            ex.printStackTrace();
	        }
	    }
	    return result;
	}

      2.3java的URL模拟form表单发送数据

//java的URL模拟form表单发送数据
	public static String urlForm(String url, Map<String, String> map) {  
        URL u = null;  
        HttpURLConnection con = null;  
        // 构建请求参数  
        StringBuffer sb = new StringBuffer();  
        if (map != null) {  
            for (Map.Entry<String, String> e : map.entrySet()) {  
                sb.append(e.getKey());  
                sb.append("=");  
                sb.append(e.getValue());  
                sb.append("&");  
            }  
            sb.substring(0, sb.length() - 1);  
        }  
        System.out.println("send_url:" + url);  
        System.out.println("send_data:" + sb.toString());  
        // 尝试发送请求  
        try {  
            u = new URL(url);  
            con = (HttpURLConnection) u.openConnection();  
             POST 只能为大写,严格限制,post会不识别  
            con.setRequestMethod("POST");  
            con.setDoOutput(true);  
            con.setDoInput(true);  
            con.setUseCaches(false);  
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");  
            osw.write(sb.toString());  
            osw.flush();  
            osw.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (con != null) {  
                con.disconnect();  
            }  
        }  
  
        // 读取返回内容  
        StringBuffer buffer = new StringBuffer();  
        try {  
            //一定要有返回值,否则无法把请求发送给server端。  
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));  
            String temp;  
            while ((temp = br.readLine()) != null) {  
                buffer.append(temp);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        return buffer.toString();  
    }  

      2.4java的URL发送get数据请求

//java的URL发送xml数据请求
	public static String sendGet(String url) {
	    OutputStreamWriter out = null;
	    BufferedReader in = null;
	    String result = "";
	
	    try {
	        URL realUrl = new URL(url);
	        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
	
	        // 发送POST请求必须设置如下两行
	        conn.setDoOutput(true);// 向连接中写入数据
	        conn.setDoInput(true);// 从连接中读取数据
	        
	        //conn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
	        conn.setUseCaches(false);//Post请求不能使用缓存
	        // 设置请求方式为POST方法
	        conn.setRequestMethod("GET");    
	
	        // 设置通用的请求属性
	        conn.setRequestProperty("accept", "*/*");
	        conn.setRequestProperty("connection", "Keep-Alive");
	        conn.connect();
	
	        // 获取URLConnection对象对应的输出流
	        out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
	        // flush输出流的缓冲
	        out.flush();
	        // 定义BufferedReader输入流来读取URL的响应
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
	        String line ;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	    } catch (Exception e) {
	        System.out.println("发送 POST 请求出现异常!"+e);
	        e.printStackTrace();
	    }
	    //使用finally块来关闭输出流、输入流
	    finally{
	        try{
	            if(out!=null){
	                out.close();
	            }
	            if(in!=null){
	                in.close();
	            }
	        }
	        catch(IOException ex){
	            ex.printStackTrace();
	        }
	    }
	    return result;
	}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HTTP协议定义了一套状态码,用于表示请求和响应的状态。以下是常见的HTTP状态码及其含义: 1xx(信息性状态码):表示请求已被接收,需要进一步处理。 - 100 Continue:服务器已接收到请求的初始部分,客户端应继续发送剩余部分。 - 101 Switching Protocols:服务器已理解并接受客户端的请求,将切换到新的协议。 2xx(成功状态码):表示请求已成功处理。 - 200 OK:请求已成功,返回所请求的资源。 - 201 Created:请求已成功处理,并创建了新资源。 - 204 No Content:请求已成功处理,但响应报文不包含实体内容。 3xx(重定向状态码):表示需要进一步操作以完成请求。 - 301 Moved Permanently:请求的资源已永久移动到新位置。 - 302 Found:请求的资源暂时移动到新位置。 - 304 Not Modified:客户端缓存的资源是最新的,无需重新传输。 4xx(客户端错误状态码):表示客户端发送的请求有错误。 - 400 Bad Request:请求语法错误,服务器无法理解。 - 403 Forbidden:服务器拒绝提供所请求的资源。 - 404 Not Found:请求的资源不存在。 5xx(服务器错误状态码):表示服务器在处理请求时发生错误。 - 500 Internal Server Error:服务器遇到错误,无法完成请求。 - 502 Bad Gateway:服务器作为网关或代理,收到无效响应。 - 503 Service Unavailable:服务器暂时无法处理请求。 这只是HTTP状态码的一部分,还有其他状态码用于表示不同的情况。详细的状态码定义可以参考HTTP协议规范。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值