java处理HTTP请求

 1 import com.diyfintech.wx.service.HttpService;
 2 import org.springframework.stereotype.Service;
 3 
 4 import java.io.BufferedReader;
 5 import java.io.InputStream;
 6 import java.io.InputStreamReader;
 7 import java.io.OutputStream;
 8 import java.net.HttpURLConnection;
 9 import java.net.URL;
10 @Service
11 public class HttpServiceImpl implements HttpService {
12 
13   //处理http请求  requestUrl为请求地址  requestMethod请求方式,值为"GET"或"POST"
14   public String httpRequest(String requestUrl,String requestMethod,String outputStr){
15     
16     StringBuffer buffer=null;
17     try{
18       URL url=new URL(requestUrl);
19       HttpURLConnection conn=(HttpURLConnection)url.openConnection();
20       conn.setDoOutput(true);
21       conn.setDoInput(true);
22       conn.setRequestMethod(requestMethod);
23       conn.connect();
24       //往服务器端写内容 也就是发起http请求需要带的参数
25       if(null!=outputStr){
26         OutputStream os=conn.getOutputStream();
27         os.write(outputStr.getBytes("utf-8"));
28         os.close();
29       }
30       //读取服务器端返回的内容
31       InputStream is=conn.getInputStream();
32       InputStreamReader isr=new InputStreamReader(is,"utf-8");
33       BufferedReader br=new BufferedReader(isr);
34       buffer=new StringBuffer();
35       String line=null;
36       while((line=br.readLine())!=null){
37         buffer.append(line);
38       }
39     }catch(Exception e){
40       e.printStackTrace();
41     }
42     return buffer.toString();
43   }
44 
45 }

 

posted @ 2017-11-29 20:41  龙芳伟  阅读(3380)  评论(0编辑  收藏  举报