请求头设置
//创建 请求
RequestBuilder requestBuilder = RequestBuilder.get().setUri("https://www.baidu.com/");
HttpUriRequest httpGet = requestBuilder.build();
/**
 * 设置请求头, eg: Accept: text/plain
 */
//单个设置
httpGet.setHeader(HttpHeaders.ACCEPT, ContentType.TEXT_PLAIN.getMimeType());
//多个设置
Header acceptHeader = new BasicHeader(HttpHeaders.ACCEPT, ContentType.TEXT_PLAIN.getMimeType());
Header contentTypeHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
httpGet.setHeaders(new Header[]{acceptHeader, contentTypeHeader});
HttpGet设置请求参数
//创建 请求
RequestBuilder requestBuilder = RequestBuilder.get().setUri("https://www.baidu.com/");
/**
 * GET请求的参数都是拼装在URL地址后方
 *      addParameter()
 *      addParameters() ---  List<NameValuePair> --- BasicNameValuePair
 */
//单个单个添加
requestBuilder.addParameter("username", "JiMu");
requestBuilder.addParameter("password", "123456");

//设置参数数组
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
BasicNameValuePair para1 = new BasicNameValuePair("username", "JiMu");
paramList.add(para1);
BasicNameValuePair para2 = new BasicNameValuePair("password", "123456");
paramList.add(para2);
requestBuilder.addParameters(paramList.toArray(new NameValuePair[paramList.size()]));

HttpUriRequest httpGet = requestBuilder.build();
//输出请求行:https://www.baidu.com/?username=JiMu&password=123456&username=JiMu&password=123456
System.out.println(httpGet.getRequestLine().getUri());
HttpPost设置请求参数
//创建 请求
HttpPost httpPost = new HttpPost("https://www.baidu.com/");
/**
 * post请求的参数是放在请求体里面的,依靠 HttpPost 实例自身的setEntity()方法来设置
 * 使用StringEntity设置 --- 可灵活设定参数格式
 */
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "JIMu");
jsonObject.put("password", "123456");
StringEntity entityParam = new StringEntity(jsonObject.toString());
//不设置时,默认是text/plain
entityParam.setContentType(ContentType.APPLICATION_JSON.toString());
httpPost.setEntity(entityParam);
//创建 请求
HttpPost httpPost = new HttpPost("https://www.baidu.com/");
/**
 * 使用UrlEncodedFormEntity来构建 --- 适用于传统表单格式的参数形式
 *      UrlEncodedFormEntity entityParam  = new UrlEncodedFormEntity(List<NameValuePair>, "UTF-8");
 *      httpPost.setEntity(entityParam);
 */
NameValuePair para1 = new BasicNameValuePair("username", "名字");
NameValuePair para2 = new BasicNameValuePair("password", "123456");
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(para1);
paramList.add(para2);
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
httpPost.setEntity(entityParam);
System.out.println("获取请求信息:" + EntityUtils.toString(httpPost.getEntity()));

 

时刻与技术进步,每天一点滴,日久一大步!!! 本博客只为记录,用于学习,如有冒犯,请私信于我。