HttpClient 4.5.3 get和post請求https post

HttpCilent 4.5.3  get 請求 post 請求,https post請求,不用參數類型的post請求java

GET請求web

CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration.
HttpGet httpGet = new HttpGet("http://www.baidu.com");
try {
	httpCilent.execute(httpGet);
} catch (IOException e) {
	e.printStackTrace();
}finally {
	try {
		httpCilent.close();//釋放資源
	} catch (IOException e) {
		e.printStackTrace();
	}
}

 GET 設置 超時時間apache

CloseableHttpClient httpCilent2 = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000)   //設置鏈接超時時間
				.setConnectionRequestTimeout(5000) // 設置請求超時時間
				.setSocketTimeout(5000)
				.setRedirectsEnabled(true)//默認容許自動重定向
				.build();
		HttpGet httpGet2 = new HttpGet("http://www.baidu.com");
		httpGet2.setConfig(requestConfig);
		String srtResult = "";
		try {
			HttpResponse httpResponse = httpCilent2.execute(httpGet2);
			if(httpResponse.getStatusLine().getStatusCode() == 200){
				srtResult = EntityUtils.toString(httpResponse.getEntity());//得到返回的結果
				System.out.println(srtResult);
			}else if(httpResponse.getStatusLine().getStatusCode() == 400){
				//..........
			}else if(httpResponse.getStatusLine().getStatusCode() == 500){
				//.............
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				httpCilent2.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

  POST請求json

//獲取可關閉的 httpCilent
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//配置超時時間
		RequestConfig requestConfig = RequestConfig.custom().
				setConnectTimeout(1000).setConnectionRequestTimeout(1000)
				.setSocketTimeout(1000).setRedirectsEnabled(true).build();
		
		HttpPost httpPost = new HttpPost("http://consentprt.dtac.co.th/webaoc/123SubscriberProcess");
		//設置超時時間
		httpPost.setConfig(requestConfig);
		//裝配post請求參數
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();  
		list.add(new BasicNameValuePair("age", "20"));  //請求參數
		list.add(new BasicNameValuePair("name", "zhangsan")); //請求參數
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");  
			//設置post求情參數
			httpPost.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(httpPost); 
	        String strResult = "";
	        if(httpResponse != null){  
	        	System.out.println(httpResponse.getStatusLine().getStatusCode());
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					strResult = EntityUtils.toString(httpResponse.getEntity());
				} else if (httpResponse.getStatusLine().getStatusCode() == 400) {
					strResult = "Error Response: " + response.getStatusLine().toString();
				} else if (httpResponse.getStatusLine().getStatusCode() == 500) {
					strResult = "Error Response: " + response.getStatusLine().toString();
				} else {
					strResult = "Error Response: " + response.getStatusLine().toString();
				}  
	        }else{
	        	
	        }
	        System.out.println(strResult);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpClient != null){
					httpClient.close(); //釋放資源
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

  Post 請求app

public static String doPost(String url, Map<String, Object> paramsMap){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().
				setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
				.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpPost.setConfig(requestConfig);
		
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : paramsMap.keySet()) {
			nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			logger.info("httpPost ===**********===>>> " + EntityUtils.toString(httpPost.getEntity()));
			HttpResponse response = httpClient.execute(httpPost);
			String strResult = "";
			if (response.getStatusLine().getStatusCode() == 200) {
				 strResult = EntityUtils.toString(response.getEntity());
				 return strResult;
			} else {
				return "Error Response: " + response.getStatusLine().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "post failure :caused by-->" + e.getMessage().toString();
		}finally {
			if(null != httpClient){
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

  

POST 請求,參數是json字符串dom

public static String doPostForJson(String url, String jsonParams){
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().
					setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
					.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
			
			httpPost.setConfig(requestConfig);
			httpPost.setHeader("Content-Type","application/json");  // 
			try {
				httpPost.setEntity(new StringEntity(jsonParams,ContentType.create("application/json", "utf-8")));
				System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
				HttpResponse response = httpClient.execute(httpPost);
				System.out.println(" code:"+response.getStatusLine().getStatusCode());
				System.out.println("doPostForInfobipUnsub response"+response.getStatusLine().toString());
				return String.valueOf(response.getStatusLine().getStatusCode());
			} catch (Exception e) {
				e.printStackTrace();
				return "post failure :caused by-->" + e.getMessage().toString();
			}finally {
				if(null != httpClient){
					try {
						httpClient.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
}

Post 請求上傳文件,模擬表單提交文件ide

 依賴:oop

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.4</version>
        </dependency>

 

public static String doPost() {
        final String url = "http://10.12.1.104:8080/hello";//
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            File imageFile = new File("D:\\captcha.jpg");
            String fileName = imageFile.getName();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            // file,相似表單中的name的值,後臺經過這個名字取文件
            builder.addBinaryBody("file", new FileInputStream(imageFile), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 執行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 將響應內容轉換爲字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

  後臺接收文件post

    @PostMapping("/hello")
    @ResponseBody
    public Map<String, String> a(MultipartHttpServletRequest multipartRequest) throws IOException {

        String filePath = System.getProperties().getProperty("user.home") + "/upload_y"; //獲取要保存的路徑
        MultipartFile file = multipartRequest.getFiles("file").get(0);
        String originalFilename = file.getOriginalFilename();
        //文件路徑
        String myfilePath = filePath + File.separator + originalFilename + UUID.randomUUID();
        file.transferTo(new File(myfilePath));
        return null;
    }

 https post ui

直接能夠用

 

public static String postByHttps(String url, Map<String, Object> paramsMap) throws Exception{
		X509TrustManager tm = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		SSLContext sslContext = SSLContext.getInstance("TLS");
		// 初始化SSL上下文
		sslContext.init(null, new TrustManager[] { tm }, null);
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setMaxConnTotal(50)
				.setMaxConnPerRoute(50).setDefaultRequestConfig(RequestConfig.custom()
						.setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build())
				.build();
		HttpPost httppost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : paramsMap.keySet()) {
			nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
		}
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			logger.info("httpsPost ===**********===>>> " + EntityUtils.toString(httppost.getEntity()));
			HttpResponse response = httpclient.execute(httppost);
			String strResult = "";
			if (response.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(response.getEntity());
				return strResult;
			} else {
				logger.info("Error Response:" + response.getStatusLine().toString());
				return "Error Response: " + response.getStatusLine().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "post failure :caused by-->" + e.getMessage().toString();
		}finally {
			if(null != httpclient){
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

我在騰訊微視玩短視頻 搜索用戶  「lei9527」

域名購買.com 後綴好域名 

 https://mi.aliyun.com/shop/38040

相關文章
相關標籤/搜索