public static void main(String[] args) {
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
String targetUrl = "http://www.fantizi5.com/";
try {
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(targetUrl), localContext);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
java http 取网页源码
response.setContentType("text/html;charSet=UTF-8");或者使用new String()的几个构造函数,重新构造一下
import java.io.InputStreamReader;import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class test { /**
* @param args
*/
public static void main(String[] args) {
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
String targetUrl = "http://www.fantizi5.com/";
try {
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(targetUrl), localContext);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println(IOUtils.toString(new InputStreamReader(response.getEntity().getContent(), "utf-8")));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
感谢各位大虾指点,结帖