android (java) 网络发送get/post请求参数设置

时间:2021-10-07 12:01:31

最近做了一段时间android网络编程方面的项目,现在总结一下android中网络连接方式,

android中网络通信分为socket编程和http编程,这里只介绍htt方面。网络请求方式可分为get请求,post两种请求方式,GET方式在进行数据请求时,会把数据附加到URL后面传递给服务器,比如常见的:http://XXX.XXX.XXX/XX.aspx?id=1,POST方式则是将请求的数据放到HTTP请求头中,作为请求头的一部分传入服务器。
所以,在进行HTTP编程前,首先要明确究竟使用的哪种方式进行数据请求的。

android中Http编程有两种:1、HttpURLConnection;2、HttpClient


首先介绍一下HttpURLConnection方式的get请求和post请求方法:


private Map<String, String> paramsValue;
String urlPath=null;

// 发送地http://192.168.100.91:8080/myweb/login?username=abc&password=123
public void initData(){

urlPath="http://192.168.100.91:8080/myweb/login";
paramsValue=new HashMap<String, String>();
paramsValue.put("username", "111");
paramsValue.put("password", "222");
}

get方式发起请求:

private boolean sendGETRequest(String path, Map<String, String> params) throws Exception {
boolean success=false;

// StringBuilder是用来组拼请求地址和参数
StringBuilder sb = new StringBuilder();
sb.append(path).append("?");
if (params != null && params.size() != 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
// 如果请求参数中有中文,需要进行URLEncoder编码 gbk/utf8
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}

URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20000);
conn.setRequestMethod("GET");

if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;
}


postt方式发起请求:

private boolean sendPOSTRequest(String path,Map<String, String> params) throws Exception{
boolean success=false;
//StringBuilder是用来组拼请求参数
StringBuilder sb = new StringBuilder();

if(params!=null &¶ms.size()!=0){

for (Map.Entry<String, String> entry : params.entrySet()) {

sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");

}
sb.deleteCharAt(sb.length()-1);
}

//entity为请求体部分内容
//如果有中文则以UTF-8编码为username=%E4%B8%AD%E5%9B%BD&password=123
byte[] entity = sb.toString().getBytes();

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(2000);
// 设置以POST方式
conn.setRequestMethod("POST");
// Post 请求不能使用缓存
// urlConn.setUseCaches(false);
//要向外输出数据,要设置这个
conn.setDoOutput(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded
//设置content-type获得输出流,便于想服务器发送信息。
//POST请求这个一定要设置
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", entity.length+"");
// 要注意的是connection.getOutputStream会隐含的进行connect。
OutputStream out = conn.getOutputStream();
//写入参数值
out.write(entity);
//刷新、关闭
out.flush();
out.close();

if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;

}

在介绍一下HttpClient方式,相比HttpURLConnection,HttpClient封装的得更简单易用一些,看一下实例:

get方式发起请求:

public String getRequest(String UrlPath,Map<String, String> params){
String content=null;
StringBuilder buf = new StringBuilder();
if(params!=null &¶ms.size()!=0){

for (Map.Entry<String, String> entry : params.entrySet()) {

buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
buf.append("&");

}
buf.deleteCharAt(buf.length()-1);
}
content= buf.toString();

HttpClient httpClient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet(content);

HttpResponse response = null;
try {
response = httpClient.execute(getMethod);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}

if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
content = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

return content;
}

postt方式发起请求:

private boolean sendPOSTRequestHttpClient(String path,Map<String, String> params) throws Exception {
boolean success = false;
// 封装请求参数
List<NameValuePair> pair = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 把请求参数变成请求体部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost对象设置发送的URL路径
HttpPost post = new HttpPost(path);
// 发送请求体
post.setEntity(uee);
// 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
success = true;
}
return success;
}


android网络交互还是很重要的,还是值得研究的,ok,好了就先写到这里了。