用Java模拟Http请求

本文介绍如何使用Java通过两种方式模拟HTTP客户端:一是利用httpclient4.x实现POST请求;二是使用JDK自带的HttpURLConnection发送POST请求。文中详细展示了设置请求头、发送请求参数及处理响应结果的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1),利用httpclient4.× 写一个http的客户端,模拟浏览器请求,
  1. publicvoidpost(List<NameValuePair>payload)throwsException{
  2. HttpPostpost=newHttpPost(uri);
  3. HttpEntityresult=null;
  4. try{
  5. UrlEncodedFormEntityentity=newUrlEncodedFormEntity(payload,
  6. charset);
  7. post.setEntity(entity);
  8. if(LOG.isDebugEnabled()){
  9. LOG.debug("sending:"+payload);
  10. }
  11. HttpResponseresponse=_httpClient.execute(post);
  12. StatusLinestatusLine=response.getStatusLine();
  13. if(statusLine.getStatusCode()!=HttpStatus.SC_OK){
  14. result=response.getEntity();
  15. StringBuildermsg=newStringBuilder();
  16. msg.append("httpresponsewithcode"
  17. +statusLine.getStatusCode());
  18. msg.append("\n");
  19. msg.append("postrequest:"+post.getURI());
  20. msg.append("\n");
  21. msg.append(statusLine.getReasonPhrase());
  22. if(result!=null){
  23. msg.append("\n\n");
  24. msg.append(EntityUtils.toString(result,"UTF-8"));
  25. msg.append("\n\n");
  26. }
  27. thrownewUmcException(msg.toString());
  28. }
  29. if(response.getEntity()!=null){
  30. BufferedReaderreader=newBufferedReader(
  31. newInputStreamReader(
  32. response.getEntity().getContent(),"UTF-8"));
  33. Stringline=null;
  34. while((line=reader.readLine())!=null){
  35. if(line.indexOf("success")<0)
  36. System.out.println(line);
  37. }
  38. }
  39. }finally{
  40. if(result!=null)
  41. try{
  42. EntityUtils.consume(result);
  43. }catch(IOExceptione){
  44. }
  45. post.abort();
  46. }
  47. }


uri是请求的地址,charset是编码“UTF-8”,List<NameValuePair>就是表单参数集
Java代码 收藏代码
  1. ClientConnectionManagerccManager=newThreadSafeClientConnManager();
  2. HttpClient_httpClient=newDefaultHttpClient(ccManager);


2) 采用JDK的HttpConnection构造http客户端,
  1. ////发送
  2. HttpURLConnectionconn=null;
  3. try{
  4. URLurl=newURL(Your_URL);
  5. conn=(HttpURLConnection)url.openConnection();
  6. conn.setRequestMethod("POST");
  7. conn.setRequestProperty("Content-Type",
  8. "application/x-www-form-urlencoded");
  9. conn.setUseCaches(false);
  10. conn.setDoOutput(true);
  11. OutputStreamWriterosw=newOutputStreamWriter(
  12. conn.getOutputStream());
  13. StringBuffersb=newStringBuffer();
  14. addPair(sb,"p1","p1value");
  15. addPair(sb,"p2","p2value");
  16. osw.write(sb.substring(0,sb.length()-1));
  17. osw.flush();
  18. BufferedReaderreader=newBufferedReader(
  19. newInputStreamReader(conn.getInputStream()));
  20. Stringline=null;
  21. sb=newStringBuffer();
  22. while((line=reader.readLine())!=null){
  23. sb.append(line);
  24. }
  25. line=sb.toString();
  26. //处理返回的字符串line
  27. return;
  28. ////
  29. }catch(IOExceptione){
  30. //handlee
  31. }finally{
  32. if(conn!=null)
  33. conn.disconnect();
  34. }///发送结束

addPair方法:
  1. publicstaticvoidaddPair(StringBuffersb,Stringname,Stringvalue){
  2. if(value==null){
  3. return;
  4. }
  5. sb.append(name);
  6. sb.append("=");
  7. sb.append(value);
  8. sb.append("&");
  9. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值