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;
}
}

你可能感兴趣的:(java)