本文主要是介绍向服务器发送请求参数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用GET方式向服务器发送请求参数
//path为请求路径,Map<String, String> params用来存放参数值,String enc编码格式
public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{
StringBuilder sb = new StringBuilder(path);
sb.append('?');
//例如提交参数为 ?method=save&title=123&timelength=10
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=')
.append(URLEncoder.encode(entry.getValue(), enc)).append('&');
}
sb.deleteCharAt(sb.length()-1);
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
if(conn.getResponseCode()==200){
return true;
}
return false
}
用POST方式向服务器发送请求参数
public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{
//例如提交参数为 ?method=save&title=123&timelength=10
StringBuilder sb = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=')
.append(URLEncoder.encode(entry.getValue(), enc)).append('&');
}
sb.deleteCharAt(sb.length()-1);
}
byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
//Content-Type: application/x-www-form-urlencoded
//Content-Length: 38
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置http协议的头字段,内容类型
conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));//设置http协议的头字段,内容长度
OutputStream outStream = conn.getOutputStream();//得到输出流对象
outStream.write(entitydata);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200){
return true;
}
return false;
}
使用HttpClient开源项目向服务器发送请求参数(可以看作是IE浏览器的API集合)
public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception{
List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();//请求参数放在List<NameValuePair>里面存放
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);//得到经过编码过后的实体数据
HttpPost post = new HttpPost(path);
post.setEntity(entitydata);
DefaultHttpClient client = new DefaultHttpClient(); //可以看作浏览器
HttpResponse response = client.execute(post);//执行请求
if(response.getStatusLine().getStatusCode()==200){
return true;
}
return false;
}
这篇关于向服务器发送请求参数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!