后台发送Http请求

get方式发送请求:

//  创建http请求
HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create(strWebUrl);
//  指定请求类型
httpWeb.Method = "get";
//  接收服务器响应结果
using (WebResponse wp = httpWeb.GetResponse())
{
    //  读出返回结果流
    using (StreamReader reader = new StreamReader(wp.GetResponseStream()))
    {
        ......
    }
}

post发送请求:

//  发送请求
HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create(strCreateMenuUrl);
//  指定请求类型
httpWeb.Method = "Post";

//  将要Post给服务器的数据写入请求创建的流中
using (Stream stream = httpWeb.GetRequestStream())
{
    stream.Write(Encoding.UTF8.GetBytes(menuJson), 0, Encoding.UTF8.GetBytes(menuJson).Length);
}
//  接收服务器响应结果
using (WebResponse wp = httpWeb.GetResponse())
{
    //  读出返回结果流
    using (StreamReader reader = new StreamReader(wp.GetResponseStream()))
    {
         .......
    }
}

转载原文:

平时用浏览器看网页的时候,点击一下submit按钮的时候其实就是给服务器发送了一个POST请求。但是如何在自己的C#程序里面实现类似的功能呢?本文给出了一个简单的范例,可以实现类似的和web server之间的POST通讯。通过程序发送POST的过程如下所示: 
1. 创建httpWebRequest对象 
HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得。 
WebRequest是获得一些列应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。所以我们的程序里面有一个对返回对象的类型进行测试的过程。 
2. 初始化HttpWebRequest对象 
这个过程提供一些http请求常用的属性:agentstring,contenttype等其中agentstring比较有意思,它是用来识别你用的浏览器名字的,通过设置这个属性你可以欺骗服务器你是一个IE,firefox甚至是mac里面的safari。很多认真设计的网站都会根据这个值来返回对用户浏览器特别优化过的代码。

3. 附加要POST给服务器的数据到HttpWebRequest对象 
附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。 
4. 读取服务器的返回信息 
读取服务器返回的时候,要注意返回数据的encoding。如果我们提供的解码类型不对会造成乱码。比较常见的是utf-8和gb2312之间的混淆,据我测试,国内的主机一般都是gb2312编码的。一般设计良好的网站会把它编码的方式放在返回的http header里面,但是也有不少网站根本没有,我们只能通过一个对返回二进制值的统计方法来确定它的编码方式。

 

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">方法</param>
        /// <param name="param">json参数</param>
        /// <returns></returns>
        public static string WebServiceApp(string url, string method, string param)
        {
            //转换输入参数的编码类型,获取bytep[]数组 
            byte[] byteArray = Encoding.UTF8.GetBytes("json=" + param);
            //初始化新的webRequst
            //1. 创建httpWebRequest对象
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + method));
            //2. 初始化HttpWebRequest对象
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
            Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            //4. 读取服务器的返回信息
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string phpend = php.ReadToEnd();
            return phpend;
           
        }

在Java后台(通常指服务器端)发送HTTP请求,可以使用多种库来处理,其中最常用的是`java.net`包下的`HttpURLConnection`或更现代的第三方库如`Apache HttpClient`、`OkHttp`或`Spring Web Client`。 1. 使用`HttpURLConnection`: ```java URL url = new URL("http://example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 或POST、PUT等 connection.setDoOutput(true); // 如果有数据需要发送 try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } System.out.println(response.toString()); } // 关闭连接 connection.disconnect(); ``` 2. 使用`Apache HttpClient`: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com/api"); try { HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { System.out.println(response.getStatusLine().toString()); try (BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()))) { String inputLine; StringBuffer content = new StringBuffer(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } System.out.println(content.toString()); } finally { response.close(); } } } catch (IOException e) { e.printStackTrace(); } finally { httpClient.close(); } ``` 3. 使用`Spring WebClient` (Spring Boot项目): ```java RestTemplate restTemplate = new RestTemplate(); // 如果配置了Spring自动注入,则不需要创建 ResponseEntity<String> response = restTemplate.getForEntity("http://example.com/api", String.class); String responseBody = response.getBody(); System.out.println(responseBody); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值