java使用HttpClient进行post和get请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Honnyee/article/details/89336688

    今天在使用一个短信接口时总是提示我请求体为空,

    我发送请求体的写法是:

 URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

     显然使用 outputStream.write是不行的,然后我查了一下他们文档里提供的demo,发现使用的是HttpClient,于是查了一下HttpClient的写法

     使用HttpClient发送post请求:

/**
	 *
	 * @param jsonObjStr 传入的内容(请求体)
	 * @param url 链接
	 * @param authorization 应要求需提供的验证值
	 * @return
	 */
public static JSONObject httpPost(String jsonObjStr, String url, String authorization){
		HttpPost post = null;
		try {
			HttpClient httpClient = HttpClientBuilder.create().build();

			post = new HttpPost(url);
			// 构造消息头
			post.setHeader("Content-type", "application/json; charset=utf-8");
			post.setHeader("Accept","application/json");
			post.setHeader("Authorization",authorization);
			// 设置超时时间
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
					.setSocketTimeout(5000).build();
			post.setConfig(requestConfig);

			// 构建消息实体
			StringEntity entity = new StringEntity(jsonObjStr, Charset.forName("UTF-8"));
			entity.setContentEncoding("UTF-8");
			// 发送Json格式的数据请求
			entity.setContentType("application/json");
			post.setEntity(entity);

			HttpResponse response = httpClient.execute(post);
			//获取响应码
			Integer status = response.getStatusLine().getStatusCode();
			//这里的status返回的是http的状态码 比如200
			logger.debug("Https请求返回状态码:[{}]",status);
			//responseEntity才是真正收到的内容
			HttpEntity responseEntity = response.getEntity();
			String result = "";
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity, "UTF-8");

			}
			EntityUtils.consume(responseEntity);
			return JSONObject.parseObject(result);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(post != null){
				try {
					post.releaseConnection();
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

收到JSONObject对象,处理就行了

发送get请求:

	/**
	 * 发送get请求
	 * @param url    路径
	 * @return
	 */
	public static JSONObject httpGet(String url){
		//get请求返回结果
		JSONObject jsonResult = null;
		try {
			HttpClient client = HttpClientBuilder.create().build();
			//发送get请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			/**请求发送成功,并得到响应**/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				/**读取服务器返回过来的json字符串数据**/
				String strResult = EntityUtils.toString(response.getEntity());
				/**把json字符串转换成json对象**/
				jsonResult = JSONObject.parseObject(strResult);
				url = URLDecoder.decode(url, "UTF-8");
			} else {
				logger.error("get请求提交失败:" + url);
			}
		} catch (IOException e) {
			logger.error("get请求提交失败:" + url, e);
		}
		return jsonResult;
	}

猜你喜欢

转载自blog.csdn.net/Honnyee/article/details/89336688