如何在java中发起http和https请求

Python015

如何在java中发起http和https请求,第1张

1.写http请求方法

[java] view plain copy

//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"

public static String httpRequest(String requestUrl,String requestMethod,String outputStr){

StringBuffer buffer=null

try{

URL url=new URL(requestUrl)

HttpURLConnection conn=(HttpURLConnection)url.openConnection()

conn.setDoOutput(true)

conn.setDoInput(true)

conn.setRequestMethod(requestMethod)

conn.connect()

//往服务器端内容 也就是发起http请求需要带的参数

if(null!=outputStr){

OutputStream os=conn.getOutputStream()

os.write(outputStr.getBytes("utf-8"))

os.close()

}

//读取服务器端返回的内容

InputStream is=conn.getInputStream()

InputStreamReader isr=new InputStreamReader(is,"utf-8")

BufferedReader br=new BufferedReader(isr)

buffer=new StringBuffer()

String line=null

while((line=br.readLine())!=null){

buffer.append(line)

}

}catch(Exception e){

e.printStackTrace()

}

return buffer.toString()

}

使用servlet

public class Test extends HttpServlet {

private static final long serialVersionUID = 1L

   

  /**

   * @see HttpServlet#HttpServlet()

   */

  public Test() {

      super()

      // TODO Auto-generated constructor stub

  }

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收get请求

// 这里写你接收request请求后要处理的操作

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收post请求

// 这里写你接收request请求后要处理的操作

}

}