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();

      //--------------------------传参-------------------------

       OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream(),"UTF-8");

      //body参数在这里put到JSONObject中
writer.write(data);

        //-----------------------------------------------------------------------

        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();
        }
    }

}

post请求案例2

package cn;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

    /**
        * 调用http接口方法
        * @param url   接口地址
        * @param data  json格式参数
        * @return
        */
       public static String SendHttpPOST(String url, String data) throws Exception { 
           String result = null; 
           //打开连接
           //要发送的POST请求url?Key=Value&Key2=Value2&Key3=Value3的形式 
           //URL requestUrl = new URL(url + "?" + requestParam); 
           URL requestUrl = new URL(url); 
           HttpURLConnection httpConn = (HttpURLConnection)requestUrl.openConnection();
    
           //加入数据 
           httpConn.setRequestMethod("POST"); 
           httpConn.setDoOutput(true);
           httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream(),"UTF-8");

           //body参数在这里put到JSONObject中

           writer.write(data);
           writer.flush();
            //获取输入流
           BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"utf-8")); 
           int code = httpConn.getResponseCode(); 
           if (HttpURLConnection.HTTP_OK == code || HttpURLConnection.HTTP_CREATED == code){
               String temp = in.readLine(); 
               /*连接成一个字符串*/ 
               while (temp != null) { 
                   if (result != null) {
                       result += temp; 
                   }else {
                       result = temp; 
                   }  
                   temp = in.readLine(); 
               } 
           } 
           return result; 
           }
public static void main(String[] args) throws Exception {
String url ="http://172.16.129.1:8080/api/v1/1785/login/login.do";//
String data ="username=interface&password=153ef57a3316a31bbb2134bd0cfe16b2";
  String s = HttpUtils.SendHttpPOST(url,data);
System.err.println(s);

}

}

 

 

 

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

 

posted @ 2015-07-08 11:54  君子笑而不语  阅读(2642)  评论(0编辑  收藏  举报