当我们采用post数据的时候有可能会遇到这种情况服务器返回403错误。这里只要我们设置一下UA欺骗一下服务器就可以了。有时候设置了windowNT的时候没有办法解决记得设置一下linux下面的。这里给出我自己封装的HTTP 的类采用的是httpclient 这个包。
public class Http {
private static Http mhttp;
private HttpClient client = null;
private Http() {
client = new DefaultHttpClient();
}
public static Http getInstance() {
if (mhttp == null) {
mhttp = new Http();
}
return mhttp;
}
public String doPost(String url, List params) {
return doPost(url, params, "UTF-8");
}
public synchronized String doPost(String url, List params, String code) {
//HttpEntity entity = new Defaulthttp
String result = null;
HttpPost post = new HttpPost(url);
HttpEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, code);
//client.getParams().setParameter(CoreConnectionPNames., arg1)
//post.addHeader("content-type", "application/x-www-form-urlencoded");
//重点就在这里
post.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
post.addHeader("Accept-Encoding", "gzip");
post.addHeader("Accept-Charset", "utf-8");
post.addHeader("Accept-Language", "en-US,en");
//post.addHeader("accept", "*/*");
post.addHeader("connection", "Keep-Alive");
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return result;
}
public synchronized String doGet(String url) {
return doGet(url, "utf-8");
}
public String doGet(String url, String code) {
String result = null;
HttpGet get = new HttpGet(url);
try {
HttpResponse httpResponse = client.execute(get);
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return result;
}
}