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
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
对于JavaHTTPClient请求multipart/form-data,你可以使用Apache HttpClient库来实现。下面是一个简单的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.HttpClients; import java.io.File; import java.io.IOException; public class MultipartFormDataExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/upload"); // 创建一个多部分实体构建器 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文本参数 builder.addTextBody("username", "John Doe"); // 添加文件参数 File file = new File("path/to/image.jpg"); builder.addBinaryBody("image", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); // 构建多部分实体 HttpEntity multipartEntity = builder.build(); // 将多部分实体设置为请求的实体 httpPost.setEntity(multipartEntity); try { // 执行请求 HttpResponse response = httpClient.execute(httpPost); // 处理响应 // ... } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码,我们使用了Apache HttpClient库来进行HTTP请求。首先,我们创建一个`HttpClient`实例,并指定要进行POST请求的URL。然后,我们创建一个`MultipartEntityBuilder`实例,用于构建多部分实体。我们可以使用`addTextBody`方法添加文本参数,使用`addBinaryBody`方法添加文件参数。最后,我们通过调用`build`方法构建多部分实体,并将其设置为POST请求的实体。最后,我们执行请求并处理响应。 希望以上的示例代码能对你有所帮助。<span class="em">1</span> #### 引用[.reference_title] - *1* [c#实现HttpClient拼接multipart/form-data形式参数post提交数据](https://download.csdn.net/download/kgo00/12091747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值