[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()
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请求后要处理的操作
}
}