httpclient 发送一个请求
httpclient版本 4.1
发送一个post请求
public static JSONObject post(String url,JSONObject json){ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); JSONObject response = null; try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s); HttpResponse res = client.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){ HttpEntity entity = res.getEntity(); String charset = EntityUtils.getContentCharSet(entity); response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset))); } } catch (Exception e) { throw new RuntimeException(e); } return response; }
模拟提交form:
private static HttpPost postForm(String url, Map<String, String> params){ HttpPost httpost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList <NameValuePair>(); Set<String> keySet = params.keySet(); for(String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } try { log.info("set utf-8 form entity to httppost"); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpost; }
get请求
public static String get(String url) { DefaultHttpClient httpclient = new DefaultHttpClient(); String body = null; log.info("create httppost:" + url); HttpGet get = new HttpGet(url); body = invoke(httpclient, get); httpclient.getConnectionManager().shutdown(); return body; }
发起一个post请求,设置超时:
需要注意各个版本设置超时的api都不相同。
还有需要注意的是3中超时:
1,连接超时:connectionTimeout 指的是连接一个url的连接等待时间。
2,读取数据超时:soTimeout 指的是连接上一个url,获取response的返回等待时间
3,SocketTimeout :定义了Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
public static String sendPostRequest(String url, String str, String contentType, String charset){ // HttpParams httpParams = new BasicHttpParams();//4.1版本 // HttpConnectionParams.setConnectionTimeout(httpParams, 5000);//建立连接超时时间,防止调用url为死链,消耗服务器io // HttpConnectionParams.setSoTimeout(httpParams, 3000);// 响应超时 // CloseableHttpClient httpClient = new DefaultHttpClient(); RequestConfig.Builder requestBuilder = RequestConfig.custom();//4.3.5版本 requestBuilder = requestBuilder.setConnectTimeout(5000); //requestBuilder = requestBuilder.setConnectionRequestTimeout(100); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); CloseableHttpClient httpClient = builder.build(); HttpPost post = new HttpPost(url); //RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); //post.setConfig(requestConfig); post.setHeader("Content-Type", contentType); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = null; try { post.setEntity(new StringEntity(str, charset)); long start = System.currentTimeMillis(); try { response = httpClient.execute(post,responseHandler); } catch (Exception ConnectionTimeoutException) {//建立连接超时异常 long p = System.currentTimeMillis() - start; log.error("sendPostRequest has a ConnectionTimeoutException timeout=> "+ p +" "+ url); }finally{ //httpClient.getConnectionManager().shutdown(); post.releaseConnection(); } } catch (Exception e) { log.error("执行HTTP Post请求" + url + "时,发生异常!", e); } return response; }
分类:
Java
, http/tcp/ip协议
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述