请求头里主要是客户端的一些基础信息,UA(user-agent)就是其中的一部分,而响应头里是响应数据的一些信息,以及服务器要求客户端如何处理这些响应数据的指令。请求头里面的关键信息如下:
响应头里的关键信息有:
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
}
添加http头信息 httppost.addHeader,Authorization, your token。
认证token httppost,addHeader,Content-Type, application/json。
httppost跟addHeader,User-Agent, imgfornote。
Authorization 是采用 basic auth 授权方式验证客户端请求,Authorization 请求头对应的值是 (basic base64编码) 。
其中 base64编码是将 用户名:密码 这种格式进行处理生成的,postman 里面有一个按钮帮助你生成 base64编码,并且自动在 header 中添加 Authorization。
Get/Post方式中的HTTP请求头,一般有多项参数。有一项是Authorization,直接填进去,就好了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)