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

Python014

如何在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()

}

实现思路就是先定义请求头内容,之后进行请求头设置。

定义请求头

LinkedHashMap<String,String>headers = new LinkedHashMap<String,String>()

headers.put("Content-type","text/xml")

headers.put("Cache-Control", "no-cache")

headers.put("Connection", "close")

给HttpPost 设置请求头

HttpPost httpPost = new HttpPost("地址")

if (headers != null) {

for (String key : headers.keySet()) {

httpPost.setHeader(key, headers.get(key))

}

}

备注:只需要在map中设置相应的请求头内容即可。根据实际需要修改即可

用servlet接收。

具体步骤是写一个类继承HttpServlet,如果是接收get请求就重写doGet(HttpServletRequest,HttpServletResponse),接收post就重写doPost(HttpServletRequest,HttpServletResponse),共同处理post和get就重写service(HttpServletRequest,HttpServletResponse)

其次在web.xml定义servlet标签,以及你这个servlet要处理的请求mapping

最后把项目部署在tomcat之类的web容器中即可。

如果使用框架的话就另当别论了,比如spring 的DispatcherServlet。当然你也可以自己写servlet。