HttpClient--傳送請求

BtWangZhi發表於2018-01-10

Maven依賴:

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>

// 頭資訊

		Map<String, String> head = new HashMap<String, String>();
		head.put("accept", "*/*");
		head.put("connection", "Keep-Alive");
		head.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		head.put("Content-Type", "application/json");

1 get請求

/**
	 * 執行GET請求
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String doGet(String url, Map<String, String> param) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 建立uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			HttpGet httpGet = new HttpGet(uri);
			response = httpclient.execute(httpGet);// 執行請求
			// 判斷返回狀態是否為200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(),
						"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

2 POST請求

/**
	 * POST傳遞form表單資料
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String doPostForm(String url, Map<String, String> param) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			// 建立引數列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
						paramList);
				httpPost.setEntity(entity);
			}
			response = httpClient.execute(httpPost);// 執行http請求
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

3 POST傳送JSON資料

/**
	 * 傳送JSON資料
	 * 
	 * @param url
	 * @param json
	 * @return
	 */
	public static String doPostJson(String url, String json) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity entity = new StringEntity(json,
					ContentType.APPLICATION_JSON);// 建立請求內容
			httpPost.setEntity(entity);
			response = httpClient.execute(httpPost);// 執行http請求
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 關閉
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

4 傳送XML資料

public static String doPostXml(String url, String xmlData) {
		logger.info("XML資料:"+xmlData);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			// 資料
			httpPost.addHeader("Content-Type","text/xml;charset=UTF-8");  
			StringEntity entity = new StringEntity(xmlData, "UTF-8");// 建立請求內容
			httpPost.setEntity(entity);
			// 執行http請求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

Java傳送Form表單
新增Form表單,包括檔案

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.5.2</version>
		</dependency>
public static String doSubmitFormIncludeFile(String url,Map<String,Object> params,File file) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(url);
            
            //檔案
            FileBody bin = new FileBody(file);
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            MultipartEntityBuilder build = entityBuilder.addPart("file", bin);
            
            //引數
            Iterator<Entry<String, Object>> mapIterator = params.entrySet().iterator();
            while(mapIterator.hasNext()) {
            	Entry<String, Object> next = mapIterator.next();
            	StringBody contentBody=new StringBody(next.getValue()+"",ContentType.MULTIPART_FORM_DATA);
            	build.addPart(next.getKey(), contentBody);
            }
            HttpEntity reqEntity = build.build();
            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
                EntityUtils.consume(resEntity);
                System.out.println(resultString);
                return resultString;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
	}

測試

String url = "http://127.0.0.1:8084/cloudai/task/uploadFile";
        Map<String,Object> params=new HashMap<>();
        params.put("a", 1);
        params.put("b", 2);
        File file=new File("D:\\a.xls");
        String doForm = doSubmitFormIncludeFile(url, params, file);
        System.out.println(doForm);
@PostMapping("/uploadFile")
    public Object uploadFile(@RequestParam Map<String,Object> params,@RequestParam("file") MultipartFile multipartFile){
        return params;
    }

參考:
https://blog.csdn.net/u010826617/article/details/80236226
https://blog.csdn.net/wsdtq123/article/details/78888734
https://blog.csdn.net/qq_18675693/article/details/53556429

相關文章