zlzyp 发表于 2017-1-7 11:08:44

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]
查看完整版本: Java用apache的HttpClient发送Post请求