如何设置一个HttpClient的请求Content-Type头

 我来答
百度网友6edd78e
2017-10-28 · 超过33用户采纳过TA的回答
知道答主
回答量:97
采纳率:37%
帮助的人:31.9万
展开全部
  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%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 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%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式相比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!=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 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!=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 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;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

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

类别

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

说明

0/200

提交
取消

辅 助

模 式