/** * @Version: 1 * @JDK: jdk 1.7 * @Module: HttpClient * 2012-11-9 - 上午9:45:47 Created by Sharp */ /*- History ********************************************** * ID DATE PERSON REASON * 1 2012-11-9 Sharp Created ********************************************** */ package com.sharp.http; import java.util.ArrayList; import java.util.List; import org.apache.http.Consts; 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; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MyClient { HttpClient client; @Before public void setUp(){ client = new DefaultHttpClient(); } @Test public void testPost(){ HttpPost post = new HttpPost("http://localhost:8081/TestServlet/hello"); try { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("name","肖鹏")); pairs.add(new BasicNameValuePair("age","25")); pairs.add(new BasicNameValuePair("sex","man")); post.setEntity(new UrlEncodedFormEntity(pairs, Consts.UTF_8)); // post.setEntity(new FileEntity(new File("C:/hello.text")));//传文件 /* * 还支持: * * AbstractHttpEntity * BasicHttpEntity * BufferedHttpEntity * ByteArrayEntity * EntityTemplate * FileEntity * HttpEntityWrapper * InputStreamEntity * SerializableEntity * StringEntity */ HttpResponse response = client.execute(post); System.out.println(response.getStatusLine()); } catch (Exception e) { e.printStackTrace(); } post.releaseConnection(); } @After public void tearDown(){ } }