0%

Java用apache的HttpClient发送Post请求 可获取返回Header

要获取网络上的网页内容有POST,和GET两种方式,Get比较简单,直接把参数放在URL结尾就OK,比如http://127.0.0.1/list.php?id=1这个URL,问号后面的就是传送的参数,id为1。但是get有个受到浏览器支持的URL最大长度的限制,而且如果传用密码之类的东西,直接写在网址里也不安全。Post相对于Get没有长度限制,也不会把数据明文放在URL结尾。 下面的例子是用Java发送Post请求,并把网页返回的内容输出。 首先看接收请求的php文件源代码:

<?php
@$pwd=$_POST["pwd"];
echo $pwd;
?>

很简单,功能就是把Post过来的pwd值输出。 下面是发送POST的JAVA代码:

package com.pocketdigi;

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 Main {
    /**
     * @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 params=new ArrayList();
        //建立一个NameValuePair数组,用于存储欲传送的参数
        params.add(new BasicNameValuePair("pwd","2544"));
        //添加参数
        httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
        //设置编码
        HttpResponse response=new DefaultHttpClient().execute(httppost);
        //发送Post,并返回一个HttpResponse对象
                //Header header = response.getFirstHeader("Content-Length");
        //String Length=header.getValue();
                // 上面两行可以得到指定的Header
        if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
            String result=EntityUtils.toString(response.getEntity());
            //得到返回的字符串
            System.out.println(result);
            //打印输出
                       //如果是下载文件,可以用response.getEntity().getContent()返回InputStream
        }
    }
}

2011年5月24日注:处理乱码,对取得的result字符串作下转换,

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

网页编码为GBK