import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class urltest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
URL url=new URL("http://www.baidu.com");
HttpURLConnection ourl= (HttpURLConnection)url.openConnection();
InputStream inStream=ourl.getInputStream();
ByteArrayOutputStream nei= new ByteArrayOutputStream();
byte[] shu= new byte[1024];
while(inStream.read(shu)!=-1){
nei.write(shu);
}
byte[] data=nei.toByteArray();
String s=new String(data,"gbk");
nei.close();
inStream.close();
System.out.println(s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/********
@POST后台处理
*******/
public class urltest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
URL url=new URL("http://www.baidu.com");
HttpURLConnection ourl= (HttpURLConnection)url.openConnection();
ourl.setRequestMethod("POST");
ourl.setDoOutput(true);//设置是否传入参数
StringBuffer params = new StringBuffer();//参数
byte[] bypes = params.toString().getBytes();
ourl.getOutputStream().write(bypes);// 输入参数
InputStream inStream=ourl.getInputStream();
ByteArrayOutputStream nei= new ByteArrayOutputStream();
byte[] shu= new byte[1024];
while(inStream.read(shu)!=-1){
nei.write(shu);
}
byte[] data=nei.toByteArray();
String s=new String(data,"gbk");
nei.close();
inStream.close();
System.out.println(s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
浙公网安备 33010602011771号