httpClient中post请求并传送form-data数据

     开发中遇到对接需求时候,被要求用post请求传form-data数据的时候一脸懵逼,最后经过多重摸索百度后终于找到方法,废话不多说,直接上代码。

​
​

public StringBuffer connection(Map<String,String> map, String strURL) {
		// start
		HttpClient httpClient = new HttpClient();
		 
		httpClient.getHostConfiguration().setProxy("10.192.10.101", 8080); //设置代理
		httpClient.getParams().setAuthenticationPreemptive(true);  

		HttpConnectionManagerParams managerParams = httpClient
				.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(30000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(120000);

		PostMethod postMethod = new PostMethod(strURL);
		// 将请求参数XML的值放入postMethod中
		String strResponse = null;
		StringBuffer buffer = new StringBuffer();
		// end
		try {
			//设置参数到请求对象中,重点是map中有几个参数NameValuePair数组也必须设置成几,不然
            //会空指针异常
			NameValuePair[] nvps = new NameValuePair[4];
			int index = 0;
			for(String key : map.keySet()){
				nvps[index++]=new NameValuePair(key, map.get(key));
			}
			postMethod.setRequestBody(nvps);
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) {
				throw new IllegalStateException("Method failed: "
						+ postMethod.getStatusLine());
			}
			BufferedReader reader = null;
			reader = new BufferedReader(new InputStreamReader(
					postMethod.getResponseBodyAsStream(), "UTF-8"));
			while ((strResponse = reader.readLine()) != null) {
				buffer.append(strResponse);
			}
		} catch (Exception ex) {
			throw new IllegalStateException(ex.toString());
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}
		return buffer;
	}

​

​

另附上get请求代码:

​
public String httpGetInfo(String strURL) throws Exception{
		CloseableHttpClient httpCilent2 = HttpClients.createDefault();
		HttpHost proxy = new HttpHost("10.192.10.101", 8080);
		RequestConfig requestConfig = RequestConfig.custom()
				.setProxy(proxy)//设置代理
				.setConnectTimeout(30000)   //设置连接超时时间
				.setConnectionRequestTimeout(120000) // 设置请求超时时间
				.setSocketTimeout(120000)
				.setRedirectsEnabled(true)//默认允许自动重定向
				.build();
		HttpGet httpGet2 = new HttpGet(strURL);
		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();
			}
		}
		return srtResult;
	}

​
发布了3 篇原创文章 · 获赞 0 · 访问量 5305

猜你喜欢

转载自blog.csdn.net/cjlcc/article/details/83504381