Servlet发送Http请求

今日遇到一个需求,android注册,短信验证码功能。

android请求我服务端,我请求tosms.cn发送验证码短信给android,于是需要在Servlet中发送Http请求

package org.helloword;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpInvoker {

    public static String STR_URL = "http://localhost:8080/JsonProject/servlet/JsonServlet?action_flag=person";

    public static void readContentFromGet() throws IOException {
        STR_URL = STR_URL + "&param=paramstr";
        URL getUrl = new URL(STR_URL);
        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
        connection.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        System.out.println("=============get================");
        String lines;
        while ((lines = reader.readLine()) != null) {
            System.out.println(lines);
        }
        reader.close();
        connection.disconnect();
    }

    public static void readContentFromPost() throws IOException {
        URL postUrl = new URL(STR_URL);
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setDoOutput(true); //post这个地方设置为true
        connection.setDoInput(true);
        connection.setRequestMethod("POST");// Post 请求不能使用缓存
        connection.setUseCaches(false);// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
        connection.setInstanceFollowRedirects(true);// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
        // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
        // 要注意的是connection.getOutputStream会隐式的进行connect。
        connection.connect();

      //--------------------------传参-------------------------
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      String content = "account=" + URLEncoder.encode("一个大肥人 a fat man", "UTF-8");
      content +=       "&pswd="  + URLEncoder.encode("两个个大肥人2 fat men", "UTF-8");;
      out.writeBytes(content);
      /*
      在接收端,这样获取参数:
      String name = request.getParameter("account");
      String pswd = request.getParameter("pswd");
      //System.out.println(new String(name.getBytes("iso-8859-1"),"UTF-8"));
      //System.out.println(new String(pswd.getBytes("iso-8859-1"),"UTF-8"));
      */
      //-----------------------------------------------------------------------

 

 



        out.flush();
        out.close(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        System.out.println("=============post================");
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        connection.disconnect();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            readContentFromGet();
            readContentFromPost();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

 

附上源代码http://down.51cto.com/data/2066142

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Servlet发送POST请求可以使用以下步骤: 1. 创建一个URL对象,指定请求的目标地址。 ``` URL url = new URL("http://example.com/path/to/target"); ``` 2. 打开URL连接并设置请求方法为POST。 ``` HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); ``` 3. 设置请求头信息(可选)。 ``` connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); ``` 4. 设置请求体内容(如果有)。 ``` String requestBody = "param1=value1&param2=value2"; connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody.getBytes()); outputStream.flush(); outputStream.close(); ``` 5. 获取响应结果。 ``` int responseCode = connection.getResponseCode(); String responseBody = ""; if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { responseBody += line; } reader.close(); inputStream.close(); } ``` 完整的示例代码如下: ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String targetUrl = "http://example.com/path/to/target"; String requestBody = "param1=value1&param2=value2"; URL url = new URL(targetUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody.getBytes()); outputStream.flush(); outputStream.close(); int responseCode = connection.getResponseCode(); String responseBody = ""; if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { responseBody += line; } reader.close(); inputStream.close(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值