java post数据服务器拒绝的解决方法

时间:2025-02-13 08:13:26

当我们采用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<NameValuePair> params) {
		return doPost(url, params, "UTF-8");
	}

	public synchronized String doPost(String url, List<NameValuePair> params, String code) {
		//HttpEntity entity = new Defaulthttp
		String result = null;
		HttpPost post = new HttpPost(url);
		HttpEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(params, code);
			//().setParameter(CoreConnectionPNames., arg1)
			//("content-type", "application/x-www-form-urlencoded");  
//重点就在这里
			("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");  
			("Accept-Encoding", "gzip"); 
			("Accept-Charset", "utf-8"); 
			("Accept-Language", "en-US,en");
			//	("accept", "*/*");
			("connection", "Keep-Alive");
			(entity);
			HttpResponse httpResponse = (post);
			if (httpResponse != null && ().getStatusCode() == 200) {
				result = (());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			();
		} 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 = (get);
			if (httpResponse != null && ().getStatusCode() == 200) {
				result = (());
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			();
		} finally {

		}
		return result;
	}
}