Skip to content- 要获取网络上的网页内容有POST,和GET两种方式,Get比较简单,直接把参数放在URL结尾就OK,比如<a href="http://127.0.0.1/list.php?id=1">http://127.0.0.1/list.php?id=1</a>这个URL,问号后面的就是传送的参数,id为1。但是get有个受到浏览器支持的URL最大长度的限制,而且如果传用密码之类的东西,直接写在网址里也不安全。Post相对于Get没有长度限制,也不会把数据明文放在URL结尾。
- 下面的例子是用Java发送Post请求,并把网页返回的内容输出。
- 首先看接收请求的php文件源代码:
- <pre class="html" name="code"><?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;
-
-
-
-
- public class Main {
-
-
-
-
-
- public static void main(String[] args) throws Exception {
-
- String url="http://localhost/newspaper/test/1.php";
-
- HttpPost httppost=new HttpPost(url);
-
- List<NameValuePair> params=new ArrayList<NameValuePair>();
-
- params.add(new BasicNameValuePair("pwd","2544"));
-
- httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
-
- HttpResponse response=new DefaultHttpClient().execute(httppost);
-
-
-
-
- if(response.getStatusLine().getStatusCode()==200){
- String result=EntityUtils.toString(response.getEntity());
-
- System.out.println(result);
-
-
- }
- }
- }
-
-
- 2011年5月24日注:处理乱码,对取得的result字符串作下转换,
-
- result=new String(result.getBytes("ISO-8859-1"),"GBK")
-
-
- 网页编码为GBK