android怎么在网络请求头里加参数

 我来答
huanglenzhi
推荐于2016-05-19 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
采纳数:117538 获赞数:517195
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。

向TA提问 私信TA
展开全部
  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请求方法:

  [java] view
plaincopyprint?

  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");

  }

  
  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方式发起请求:

  [java] view
plaincopyprint?

  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;

  }
  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方式发起请求:

  [java] view
plaincopyprint?

  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;

  

  }
  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方式发起请求:

  [java] view
plaincopyprint?

  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;

  }
  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方式发起请求:

  [java] view
plaincopyprint?

  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;

  }
  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;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式