Posted on 2009-05-22 23:31
Gavin.lee 阅读(1439)
评论(1) 编辑 收藏 所属分类:
java SE & EE
java 对HTTP网络协议的资源请求,java api上是这样说的:“每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。”
说的再说都没用,用途简单一句话,java程序向web请求资源的。听老前辈说我这个会有问题,说是有时候不能读取完整数据。不过我是幸运的,用到现在没出现问题,先不管了。
注:在这个实例开发中,我参考了很多资料,对我的帮助都很大,实例的成功要归属这些高手们,注释主要参考下面这位仁兄。
http://www.blogjava.net/supercrsky/articles/247449.html
2009年6月29日14:07:13 PS: 对编码机制做了点改善
package com.yixun.wap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/** *//**
*
* @descripte use java.net.HttpURLConnection to request resource form web.
* @author Gavin.lee
* @date 2009-5-23 12:21:00
* @version 1.0
*/

public class TransactionCenter
{
private URL url;
private HttpURLConnection urlconn;

String inencoding;
String outencoding;

public TransactionCenter(String inencoding, String outencoding)
{
this.inencoding = inencoding;
this.outencoding = outencoding;
}

public String connect(String params, String postUrl)
{
BufferedReader br = null;
String response = "", brLine = "";

try
{
//params=URLEncoder.encode(params,"GB2312"); //use URLEncoder.encode for encode the params

url = new URL(postUrl);
urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestProperty("user-agent","mozilla/4.7 [en] (win98; i)"); //set request header
urlconn.setRequestProperty("X-Forwarded-For", "127.0.0.1");
urlconn.setConnectTimeout(30000);
urlconn.setReadTimeout(30000);
urlconn.setRequestMethod("POST"); // request method, default GET
urlconn.setUseCaches(false); //Post can not user cache
urlconn.setDoOutput(true); //set output from urlconn
urlconn.setDoInput(true); //set input from urlconn
OutputStream out = urlconn.getOutputStream();
out.write(params.getBytes(outencoding));
out.flush();
out.close(); // output stream close,That's means need not to post data to this outputstream

br = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), inencoding));
while((brLine = br.readLine())!=null)
response =(new StringBuilder(String.valueOf(response))).append(brLine).toString();

} catch (Exception e)
{
e.printStackTrace();

} finally
{

try
{

if(br != null)
{
br.close();
}

} catch (IOException e)
{
System.out.println("input stream close fail");
}
urlconn.disconnect();
}
return response;
}


public static void main(String[] args)
{
TransactionCenter tc = new TransactionCenter("GBK", "GBK");
String response = tc.connect("c_id=10041&cpid=5&c_type=1&lotid=1&expect=08059","http://inter.boss.com/interface/client/requestwap.php?");
System.out.println(response);
}
}