get请求content-type(get请求contentlength)
如何设置一个HttpClient的请求Content-Type头
android网络通信socket编程http编程介绍htt面网络请求式get请求post两种请求式GET式进行数据请求数据附加URL面传递给服务器比见:POST式则请求数据放HTTP请求作请求部传入服务器
所进行HTTP编程前首先要明确究竟使用哪种式进行数据请求
androidHttp编程两种:1、HttpURLConnection;2、HttpClient
首先介绍HttpURLConnection式get请求post请求:
[java] view
plaincopyprint?
private Map paramsValue;
String urlPath=null;
// 发送
public void initData(){
urlPath="";
paramsValue=new HashMap();
paramsValue.put("username", "111");
paramsValue.put("password", "222");
}
private Map paramsValue;
String urlPath=null;
// 发送
public void initData(){
urlPath="";
paramsValue=new HashMap();
paramsValue.put("username", "111");
paramsValue.put("password", "222");
}
get式发起请求:
[java] view
plaincopyprint?
private boolean sendGETRequest(String path, Map params) throws Exception {
boolean success=false;
// StringBuilder用组拼请求址参数
StringBuilder sb = new StringBuilder();
sb.append(path).append("?");
if (params != null params.size() != 0) {
for (Map.Entry 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 params) throws Exception {
boolean success=false;
// StringBuilder用组拼请求址参数
StringBuilder sb = new StringBuilder();
sb.append(path).append("?");
if (params != null params.size() != 0) {
for (Map.Entry 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 params) throws Exception{
boolean success=false;
//StringBuilder用组拼请求参数
StringBuilder sb = new StringBuilder();
if(params!=null ?ms.size()!=0){
for (Map.Entry 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%BDpassword=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 params) throws Exception{
boolean success=false;
//StringBuilder用组拼请求参数
StringBuilder sb = new StringBuilder();
if(params!=null ?ms.size()!=0){
for (Map.Entry 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%BDpassword=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式相比HttpURLConnectionHttpClient封装更简单易用些看实例:
get式发起请求:
[java] view
plaincopyprint?
public String getRequest(String UrlPath,Map params){
String content=null;
StringBuilder buf = new StringBuilder();
if(params!=null ?ms.size()!=0){
for (Map.Entry 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!=nullresponse.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 params){
String content=null;
StringBuilder buf = new StringBuilder();
if(params!=null ?ms.size()!=0){
for (Map.Entry 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!=nullresponse.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 params) throws Exception {
boolean success = false;
// 封装请求参数
List pair = new ArrayList();
if (params != null !params.isEmpty()) {
for (Map.Entry 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 params) throws Exception {
boolean success = false;
// 封装请求参数
List pair = new ArrayList();
if (params != null !params.isEmpty()) {
for (Map.Entry 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请求细节——Content-Type
值得一提的是 :get请求的headers中没有content-type这个字段,因为get请求不存在请求实体部分,键值对参数放置在 URL 尾部,因此请求头不需要设置 Content-Type 字段。
有的时候服务器接受不到传值,可以先确认下服务器接受的编码类型。
headers 设置 { ‘content-type’: ’application/x-www-form-urlencoded’ }:代表参数以 键值对字符串 传递。
headers 设置 { ‘content-type’: ’application/json’ }:代表参数以 序列化后的json字符串 传递(json形式的优点是它可以传递结构复杂的数据形式,比如对象里面嵌套数组这样的形式等)。
当 content-type 为 multipart/form-data 时,既可以 上传二进制数据 ( 例如图片、mp3、文件 ),也可以 上传键值对 。(因为它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开)
此时的传输数据的body必须是FormData的实例,然后通过append方法添加参数。
let formData = new FormData();
formData.append("parameter", "value");
额外提一个小点 :
默认情况下,axios将JavaScript对象序列化为JSON,所以要以application / x-www-form-urlencoded格式发送数据时,可以引入qs库编码数据( CDN )。
JSON.stringfy() 和 qs.stringfy() 的区别:
再提一个与内容无关的点:
关于跨域,现在基本上不会由前端用jsonp去解决,因为jsonp很明显的弊端是只能get请求,不能进行较为复杂的post和其它请求。现在基本都是服务器实现CORS接口来解决。(可以看下阮一峰的 跨域资源共享 CORS 详解 )

http请求中的content-type
Content-Type属性指定请求和响应的 HTTP 内容类型。如果未指定 ContentType,默认响应的内容类型为 text/html ,默认请求的内容类型为 application/x-www-form-urlencoded 。Content-Type一般只存在于Post方法中,因为Get方法是不含“body”的,它的请求参数都会被编码到url后面,所以在Get方法中加Content-type是无用的。
在 nginx 中有个配置文件 mime.types ,主要是标示 Content-Type 的文件格式。
下面是几个 常见的 Content-Type :
application/x-www-form-urlencoded 是常用的表单发包方式,普通的表单提交,或者 js 发包,默认都是通过这种方式,数据被编码为key/value格式发送到服务器。
multipart/form-data 用在 发送文件的POST包 。
Multipart/form-data的请求头必须包含一个特殊的头信息 : Content-Type , 且其值也必须规定为multipart/form-data , 同时还需要规定一个 内容分割符 即 boundary 用于分割请求体中的多个POST的内容 , 如文件内容和文本内容自然需要分割开来 , 不然接收方就无法正常解析和还原这个文件了。
text/xml 微信用的是这种数据格式发送请求的。XML-RPC(XML Remote Procedure Call)是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。
application\json HTTP通信中并不存在所谓的json,而是将string转成json罢了,也就是,application/json可以将它理解为text/plain,普通字符串。
application\xml XML数据格式
MDN Content-Type
理解HTTP之Content-Type
四种常见的POST提交数据方式
怎么获取http请求的content-type
getProtocol():获取请求使用的通信协议,如http/1.1等
getServletPath():获取请求的JSP也面所在的目录。
getContentLength():获取HTTP请求的长度。
getMethod():获取表单提交信息的方式,如POST或者GET。
getHeader(String s):获取请求中头的值。一般来说,S参数可取的头名有accept,referrer、accept-language、content-type、accept-encoding、user-agent、host、cookie等,比如,S取值user-agent将获得用户的浏览器的版本号等信息。
getHeaderNames():获取头名字的一个枚举。
getHeaders(String s):获取头的全部值的一个枚举。
getRemoteAddr():获取客户的IP地址。
getRemoteHost():获取客户机的名称(如果获取不到,就获取IP地址)。
getServerName():获取服务器的名称。
getServePort():获取服务器的端口。
getPaeameterNames():获取表单提交的信息体部分中name参数值的一个枚举