Java用apache的HttpClient发送Post请求

原文地址:http://www.pocketdigi.com/20110521/294.html


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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;
/**
*JDK默认没有org.apache.http包,需要先去http://hc.apache.org/downloads.cgi下载
*下载HttpClient,解压,在Eclipse中导入所有JAR
*/
public class TT {
/**
* @param args
* @throws UnsupportedEncodingException
* 这个例子为了简单点,没有捕捉异常,直接在程序入口加了异常抛出声明
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String url="http://localhost/newspaper/test/1.php";
//POST的URL
HttpPost httppost=new HttpPost(url);
//建立HttpPost对象
List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一个NameValuePair数组,用于存储欲传送的参数
params.add(new BasicNameValuePair("pwd","2544"));
//添加参数
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//设置编码
HttpResponse response=new DefaultHttpClient().execute(httppost);
//发送Post,并返回一个HttpResponse对象
if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
String result=EntityUtils.toString(response.getEntity());
//得到返回的字符串
System.out.println(result);
//打印输出
}
}
}

处理乱码,对取得的result字符串作下转换,

result=new String(result.getBytes("ISO-8859-1"),"GBK")


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值