JAVA HTTP 请求的POST提交

public class HttpPostUtils {

public static String httpPost(String urlAddress,Map<String, String> paramMap){
if(paramMap==null){
paramMap = new HashMap<String, String>();
}
String [] params = new String[paramMap.size()];
int i = 0;
for(String paramKey:paramMap.keySet()){
String param = paramKey+"="+paramMap.get(paramKey);
params[i] = param;
i++;
}
return httpPost(urlAddress, params);
}

public static String httpPost(String urlAddress,List<String> paramList){
if(paramList==null){
paramList = new ArrayList<String>();
}
return httpPost(urlAddress, paramList.toArray(new String[0]));
}

public static String httpPost(String urlAddress,String []params){
URL url = null;
HttpURLConnection con =null;
BufferedReader in = null;
StringBuffer result = new StringBuffer();
try {
url = new URL(urlAddress);
con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
String paramsTemp = "";
for(String param:params){
if(param!=null&&!"".equals(param.trim())){
paramsTemp+="&"+param;
}
}
byte[] b = paramsTemp.getBytes();
con.getOutputStream().write(b, 0, b.length);
con.getOutputStream().flush();
con.getOutputStream().close();
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
while (true) {
String line = in.readLine();
if (line == null) {
break;
}
else {
result.append(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(in!=null){
in.close();
}
if(con!=null){
con.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
}


ava.io.IOException: Server returned HTTP response code: 500 for URL: http://physics.whu.edu.cn/show.asp?id=278

java.io.IOException: Server returned HTTP response code: 403 for URL

但是自己却可以用浏览器访问,发现可能是服务器对我们这种java程序屏蔽了。

因为服务器的安全设置不接受Java程序作为客户端访问,解决方案是设置客户端的User Agent

url = new URL("http://physics.whu.edu.cn/show.asp?id=278");
HttpURLConnection connection = (HttpURLConnection) url.
openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

这样就可以访问了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值