java模拟post的两种方法

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class Test {
public static void main(String[] args) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.157.183:8089");

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("xmldate", "<html>你好啊啊</html>"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "GBK");
entity.setContentType("text/xml; charset=utf8");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(resEntity.getContent(), "ISO-8859-1");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
System.out.println(new String(buff, 0, length));
httpclient.getConnectionManager().shutdown();
}
}
}


import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Test2 {
public static void main(String[] args) throws Exception {
Test2 test=new Test2();

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
test.httpPost("http://192.168.157.183:8089",formparams);
}

public String httpPost(String url, List<NameValuePair> nvps) throws Exception {
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse httpResp = httpclient.execute(post);
try {
if (httpResp.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResp.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
// 保证连接能释放回管理器
EntityUtils.consume(entity);
}
}
} finally {
httpResp.close();
httpclient.close();
}
return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值