訪問不同的URL地址

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AccessDifferentURL extends HttpServlet {

    private static final long serialVersionUID = -8149855780326415302L;
    static HttpURLConnection con = null;

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {

        try {
            // get the xml of request.
            final String xml = req.getParameter("xml");
            // get Access Service URL.
            final URL url = new URL("http://192.168.1.100:8080/helloWorld");
            con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "text/xml;charset=UTF-8");
            con.setRequestProperty("Connection", "close");
            con.getOutputStream().write(xml.getBytes());
            con.getOutputStream().flush();
            con.getOutputStream().close();

            // return response code.
            final int code = con.getResponseCode();
            if (code < 300) {
                final String epcResponse = getResponseData(con.getInputStream());
                resp.setContentType("text/xml;charset=utf-8");
                final OutputStream outStream = resp.getOutputStream();
                outStream.write(epcResponse.getBytes("UTF-8"));
                outStream.close();
            }
            con.disconnect();

        } catch (final IOException io) {
            io.printStackTrace();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 將ResponseStream轉化爲字符串
     * 
     * */
    public static String getResponseData(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = reader.readLine();
        StringBuffer sb = new StringBuffer();
        while (line != null) {
            sb.append(line);
            line = reader.readLine();
        }
        in.close();
        
        return sb.toString();
    }
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章