import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class HttpClientTests {
public static void main(String[] args) throws IOException{
HttpClient client=new DefaultHttpClient();
//POST url
String posturl="http://localhost:8080/a.action";
//建立HttpPost对象
HttpPost httpPost=new HttpPost(posturl);
//建立一个NameValuePair数组,用于存储欲传递的参数
List params=new ArrayList();
//添加参数
params.add(new BasicNameValuePair("start", "0"));
params.add(new BasicNameValuePair("size", "14"));
params.add(new BasicNameValuePair("sortType", "hot"));
//设置编码
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//发送Post,并返回一个HttpResponse对象
HttpResponse response=new DefaultHttpClient().execute(httpPost);
//可以得到指定的header
//
Header header = response.getFirstHeader("Content-Length");
// String Length=header.getValue();
// System.out.println(header.getName());
//如果状态码是200,则正常返回
if(response.getStatusLine().getStatusCode()==200){
//获得返回的字符串
String result=EntityUtils.toString(response.getEntity());
//打印输出
System.err.println(result);
//如果是下载的文件,可以用response.getEntity().getContent返回InputStream
}
}
}