Java发送http请求
一 创建maven项目
二 导入依赖
<!-- httpclient 依赖--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!--引入json相关包--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
三 封装post方法
public class Test { public static byte[] encrypt(String content, String password) { try { byte[] enCodeFormat = password.getBytes(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(1, key); return cipher.doFinal(byteContent); } catch (Exception e) { e.printStackTrace(); } return null; } public static String jsonFormat(String resString){ StringBuffer jsonForMatStr = new StringBuffer(); int level = 0; for(int index=0;index<resString.length();index++)//将字符串中的字符逐个按行输出 { //获取s中的每个字符 char c = resString.charAt(index); //level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) { jsonForMatStr.append(getLevelStr(level)); } //遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行 switch (c) { case '{': case '[': jsonForMatStr.append(c + "\n"); level++; break; case ',': jsonForMatStr.append(c + "\n"); break; case '}': case ']': jsonForMatStr.append("\n"); level--; jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(c); break; default: jsonForMatStr.append(c); break; } } return jsonForMatStr.toString(); } private static String getLevelStr(int level) { StringBuffer levelStr = new StringBuffer(); for (int levelI = 0; levelI < level; levelI++) { levelStr.append("\t"); } return levelStr.toString(); } public static String post(String url, String headers, String params){ System.out.println("请求地址:" + url); System.out.println("请求参数:"); System.out.println(jsonFormat(params)); // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 设置请求内容 httpPost.setEntity(new ByteArrayEntity(params.getBytes())); // 设置自定义请求头 if (!headers.isEmpty()) { JSONObject jh = JSON.parseObject(headers); for (String h : jh.keySet()) { if (h.equals("Content-Type")) { httpPost.addHeader(h, jh.getString(h)); } else { // 设置公共请求头 httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); } httpPost.addHeader(h, jh.getString(h)); } } else { // 设置公共请求头 httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); } // 执行http请求 response = httpClient.execute(httpPost); //获取响应数据 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity());// 返回json字符串格式: } System.out.println("响应参数:"); System.out.println(jsonFormat(resultString)); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static void main(String[] args) { String data = "{\"amount\":64.39}"; String decrypt_data = new String(Base64.encodeBase64(encrypt(data, "xxxxx_PASSWORD"))); System.out.println(decrypt_data); String params = String.format("{\"decrypt_data\":%s,\"data\":\"%s\"}",data, decrypt_data); String url = "http://xxxxx/a/b/"; post(url, "", params); } }