URL和HttpURLConnection的使用(向服务器发送请求,然后返回struts版)
2011-11-01 13:26
726 查看
针对JDK中的URLConnection连接Servlet的问题,网上有虽然有所涉及,但是只是说明了某一个或几个问题,是以FAQ的方式来解决的,而且比较零散,现在对这个类的使用就本人在项目中的使用经验做如下总结:
1:> URL请求的类别:
分为二类,GET与POST请求。二者的区别在于:
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
2:> URLConnection的对象问题:
URLConnection的对象,如下代码示例:
//下面的index.jsp由<servlet-mapping>映射到
// 一个Servlet(com.quantanetwork.getClientDataServlet)
// 该Servlet的注意点下边会提到
URL url =
new
URL( " http://localhost:8080/TestHttpURLConnectionPro/index.jsp" );
URLConnection rulConnection =
url.openConnection();//
此处的urlConnection对象实际上是根据URL的
//
请求协议(此处是http)生成的URLConnection类
//
的子类HttpURLConnection,故此处最好将其转化
//
为HttpURLConnection类型的对象,以便用到
//
HttpURLConnection更多的API.如下:
HttpURLConnection httpUrlConnection =
(HttpURLConnection) rulConnection;
3:> HttpURLConnection对象参数问题
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
//
http正文内,因此需要设为true, 默认情况下是false;
httpUrlConnection.setDoOutput(true
);
//
设置是否从httpUrlConnection读入,默认情况下是true;
httpUrlConnection.setDoInput(true
);
//
Post 请求不能使用缓存
httpUrlConnection.setUseCaches(false
);
//
设定传送的内容类型是可序列化的java对象
//
(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
httpUrlConnection.setRequestProperty("
Content-type "
, "
application/x-java-serialized-object"
);
//
设定请求的方法为"POST",默认是GET
httpUrlConnection.setRequestMethod("
POST ");
//
连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成,
httpUrlConnection.connect();
4:> HttpURLConnection连接问题:
// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,
//
所以在开发中不调用上述的connect()也可以)。
OutputStream outStrm =
httpUrlConnection.getOutputStream();
5:> HttpURLConnection写数据与发送数据问题:
// 现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。
ObjectOutputStream objOutputStrm =
new
ObjectOutputStream(outStrm);
//
向对象输出流写出数据,这些数据将存到内存缓冲区中
objOutputStrm.writeObject(new
String( "
我是测试数据 "
));
//
刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)
objOutputStm.flush();
//
关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,
//
在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
objOutputStm.close();
//
调用HttpURLConnection连接对象的getInputStream()函数,
//
将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
InputStream inStrm =
httpConn.getInputStream(); //
<===注意,实际发送请求的代码段就在这里
//
上边的httpConn.getInputStream()方法已调用,本次HTTP请求已结束,下边向对象输出流的输出已无意义,
//
既使对象输出流没有调用close()方法,下边的操作也不会向对象输出流写入任何数据.
//
因此,要重新发送数据时需要重新创建连接、重新设参数、重新创建流对象、重新写数据、
//
重新发送数据(至于是否不用重新这些操作需要再研究)
objOutputStm.writeObject(new
String( ""
));
httpConn.getInputStream();
总结:a:)HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
无论是post还是get,http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
b:) 在用POST方式发送URL请求时,URL请求参数的设定顺序是重中之重,
对connection对象的一切配置(那一堆set函数)
都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。
这些顺序实际上是由http请求的格式决定的。
如果inputStream读操作在outputStream的写操作之前,会抛出例外:
java.net.ProtocolException: Cannot write output after readinginput.......
c:) http请求实际上由两部分组成,
一个是http头,所有关于此次http请求的配置都在http头里面定义,
一个是正文content。
connect()函数会根据HttpURLConnection对象的配置值生成http头部信息,因此在调用connect函数之前,
就必须把所有的配置准备好。
d:) 在http头后面紧跟着的是http请求的正文,正文的内容是通过outputStream流写入的,
实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,
而是存在于内存缓冲区中,待outputStream流关闭时,根据输入的内容生成http正文。
至此,http请求的东西已经全部准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求
正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http
请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数
之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)
都是没有意义的了,执行这些操作会导致异常的发生。
6:> Servlet端的开发注意点:
a:) 对于客户端发送的POST类型的HTTP请求,Servlet必须实现doPost方法,而不能用doGet方法。
b:)用HttpServletRequest的getInputStream()方法取得InputStream的对象,比如:
InputStream inStream = httpRequest.getInputStream();
现在调用inStream.available()(该方法用于“返回此输入流下一个方法调用可以不受阻塞地
从此输入流读取(或跳过)的估计字节数”)时,永远都反回0。试图使用此方法的返回值分配缓冲区,
以保存此流所有数据的做法是不正确的。那么,现在的解决办法是
Servlet这一端用如下实现:
InputStream inStream = httpRequest.getInputStream();
ObjectInputStream objInStream = newObjectInputStream(inStream);
Object obj = objInStream.readObject();
// 做后续的处理
// 。。。。。。
// 。。。 。。。
而客户端,无论是否发送实际数据都要写入一个对象(那怕这个对象不用),如:
ObjectOutputStream objOutputStrm = newObjectOutputStream(outStrm);
objOutputStrm.writeObject(new String("")); // 这里发送一个空数据
// 甚至可以发一个null对象,服务端取到后再做判断处理。
objOutputStrm.writeObject(null);
objOutputStrm.flush();
objOutputStrm.close();
注意:上述在创建对象输出流ObjectOutputStream时,如果将从HttpServletRequest取得的输入流
(即:newObjectOutputStream(outStrm)中的outStrm)包装在BufferedOutputStream流里面,
则必须有objOutputStrm.flush();这一句,以便将流信息刷入缓冲输出流.如下:
ObjectOutputStream objOutputStrm = new ObjectOutputStream(newBufferedOutputStream(outStrm));
objOutputStrm.writeObject(null);
objOutputStrm.flush(); // <======此处必须要有.
objOutputStrm.close();
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout",超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout",超时毫秒数字符串);
其中:sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)
例如:
System.setProperty("sun.net.client.defaultConnectTimeout","30000");
System.setProperty("sun.net.client.defaultReadTime
Java中可以使用HttpURLConnection来请求WEB资源。
HttpURLConnection对象不能直接构造,需要通过URL.openConnection()来获得HttpURLConnection对象,示例代码如下:
String szUrl =
" http://www.ee2ee.com/ "
;
URL url
=
new URL(szUrl);
HttpURLConnection urlCon =
(HttpURLConnection)url.openConnection();
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout",超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout",超时毫秒数字符串);
其中:sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)
例如:
System.setProperty("sun.net.client.defaultConnectTimeout","30000");
System.setProperty("sun.net.client.defaultReadTimeout","30000");
JDK1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法:
setConnectTimeout:设置连接主机超时(单位:毫秒)
setReadTimeout:设置从主机读取数据超时(单位:毫秒)
例如:
HttpURLConnection urlCon =
(HttpURLConnection)url.openConnection();
urlCon.setConnectTimeout(
30000 );
urlCon.setReadTimeout(
30000 );
需要注意的是,笔者在JDK1.4.2环境下,发现在设置了defaultReadTimeout的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求,出现一次请求调用,请求服务器两次的问题(Trouble)。我认为这是JDK1.4.2的一个bug。在JDK1.5.0中,此问题已得到解决,不存在自动重发现象。out","30000");
==================================================================================================
最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。
下面的代码简单描述了如何使用HttpURLConnection发起这两种请求,以及传递参数的方法:
public class HttpInvoker ...{
publicstatic final String GET_URL = "http://localhost:8080/welcome1";
publicstatic final String POST_URL = "http://localhost:8080/welcome1";
publicstatic void readContentFromGet() throws IOException ...{
// 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
String getURL = GET_URL + "?username="
+ URLEncoder.encode("fat man", "utf-8");
URL getUrl = new URL(getURL);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
//返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
// 进行连接,但是实际上getrequest要在下一句的connection.getInputStream()函数中才会真正发到
// 服务器
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
System.out.println("=============================");
System.out.println("Contents of get request");
System.out.println("=============================");
String lines;
while ((lines = reader.readLine()) != null) ...{
System.out.println(lines);
}
reader.close();
// 断开连接
connection.disconnect();
System.out.println("=============================");
System.out.println("Contents of get request ends");
System.out.println("=============================");
}
publicstatic void readContentFromPost() throws IOException ...{
// Post请求的url,与get不同的是不需要带参数
URL postUrl = new URL(POST_URL);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post cannot use caches
// Post 请求不能使用缓存
connection.setUseCaches(false);
// This method takes effects to
// every instances of this class.
//URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
//意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// The URL-encoded contend
// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
String content = "firstname=" + URLEncoder.encode("一个大肥人","utf-8");
//DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(content);
out.flush();
out.close(); // flush and close
BufferedReader reader = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
String line;
System.out.println("=============================");
System.out.println("Contents of post request");
System.out.println("=============================");
while ((line = reader.readLine()) != null) ...{
System.out.println(line);
}
System.out.println("=============================");
System.out.println("Contents of post request ends");
System.out.println("=============================");
reader.close();
connection.disconnect();
}
publicstatic void main(String[] args) ...{
// TODO Auto-generated method stub
try ...{
readContentFromGet();
readContentFromPost();
} catch (IOException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上面的readContentFromGet()函数产生了一个get请求,传给servlet一个username参数,值为"fatman"。
readContentFromPost()函数产生了一个post请求,传给servlet一个firstname参数,值为"一个大肥人"。
HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到HttpURLConnection.getInputStream()这个函数里面才正式发送出去。
在readContentFromPost()中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。
http请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。
紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。
至此,http请求的东西已经准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。
本节深入学习post请求。
上节说道,post请求的OutputStream实际上不是网络流,而是写入内存,在getInputStream中才真正把写道流里面的内容作为正文与根据之前的配置生成的httprequest头合并成真正的http request,并在此时才真正向服务器发送。
HttpURLConnection.setChunkedStreamingMode函数可以改变这个模式,设置了ChunkedStreamingMode后,不再等待OutputStream关闭后生成完整的httprequest一次过发送,而是先发送httprequest头,正文内容则是网路流的方式实时传送到服务器。实际上是不告诉服务器http正文的长度,这种模式适用于向服务器传送较大的或者是不容易获取长度的数据,如文件。下面以一段代码讲解一下,请与Http学习之使用HttpURLConnection发送post和get请求中的readContentFromPost()函数作对比:
publicstatic void readContentFromChunkedPost() throws IOException...{
URL postUrl = new URL(POST_URL);
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setChunkedStreamingMode(5);
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "firstname=" +URLEncoder.encode("一个大肥人 "
+
" "
+
"asdfasfdasfasdfaasdfasdfasdfdasfs", "utf-8");
out.writeBytes(content);
out.flush();
out.close(); // 到此时服务器已经收到了完整的httprequest了,而在readContentFromPost()函数里,要等到下一句服务器才能收到http请求。
BufferedReader reader = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
out.flush();
out.close(); // flush and close
String line;
System.out.println("=============================");
System.out.println("Contents of post request");
System.out.println("=============================");
while ((line = reader.readLine()) != null) ...{
System.out.println(line);
}
System.out.println("=============================");
System.out.println("Contents of post request ends");
System.out.println("=============================");
reader.close();
connection.disconnect();
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dodolzg/archive/2010/10/20/5954191.aspx
=============================================================================================
*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.superMail.action.myFocus;
//import java.io.BufferedReader;
import java.io.DataOutputStream;
//import java.io.IOException;
import java.io.InputStream;
//import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
//import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
//import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
//import org.w3c.dom.Text;
//import org.xml.sax.SAXException;
public class Test2 extends Action {
List obj=newArrayList(0);
@SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
public ActionForward execute(ActionMapping mapping, ActionFormform,
HttpServletRequest request, HttpServletResponse response) {
String url="http://218.204.254.218:8080/richlifeApp/share/pc_getWholeCatalog";
StringxmlData="<?xml version='1.0' encoding='UTF-8'standalone='no' ?>"
+"<getWholeCatalogownerMSISDN="15989202763"/>";
String method="GET";
String auth="BasicMTU5ODkyMDI3NjM6U1QtMTQ2NzMtVVZUbTVMVVVRWlpOQUxkQVVrWlBGM21XbWdvcFhDVG5IUFEtMjBfXzE=";
HashMap paras=newHashMap();
HashMap heads=newHashMap();
//Vector m_vec=newVector();
heads.put("pragma","no-cache");
heads.put("Accept-Language","UTF-8");
heads.put("Authorization",auth);
//向服务器发送消息,并获得返回的“输入流”:
InputStreamin=getInput(url,xmlData,method,paras,heads);
//以下用于测试:
//为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db =null;
try {
db =dbf.newDocumentBuilder();
} catch(ParserConfigurationException pce) {
System.err.println(pce); // 出异常时输出异常信息,然后退出,下同
System.exit(1);
}
Document doc = null;
try {
System.out.println("开始解析XML结构体:");
doc =db.parse(in);
} catch (Exception e) {
e.printStackTrace();
}
//下面是解析XML的全过程,比较简单,先取根元素"学生花名册"
Element result =doc.getDocumentElement();
// 取"学生"元素列表
NodeList catalogNodes =result.getElementsByTagName_r("catalogNode");
System.out.println(catalogNodes.getLength());
for (int i = 0; i< catalogNodes.getLength(); i++) {
//依次取每个"学生"元素
ElementcatalogNode = (Element) catalogNodes.item(i);
StringcatalogName=catalogNode.getAttribute("catalogName");
StringisShared=catalogNode.getAttribute("isShared");
//打印出节点的“属性值”:
System.out.println("catalogName :"+catalogName);
System.out.println("isShared:"+isShared);
MyFoldermf=new MyFolder(catalogName,isShared);
//把获得的值放到缓存里面:
obj.add(mf);
}
HttpSessionsen=request.getSession();
sen.setAttribute("obj",obj);
returnmapping.findForward("ReturnJspMap");
}
@SuppressWarnings("unchecked")
private InputStream getInput(String url,String xmlData,
Stringmethod,HashMap paras,HashMap headers){
//用来放“从服务器收到的‘输入流’”:
InputStream in = null;
String arguments = null;
//用来向“服务器”发送请求时,服务器的“地址”:
URL requestUrl=null;
//与服务建立“连接”后,获得的“连接”的“对象”,
//包含与“服务器”相关的各种“连接,流,资源:
URLConnection con=null;
if (url == null){
System.out.println("请求的服务器路径为 null !");
}
//加上“请求”的附加数据:比如?user=lijun&pwd=lijun
if (paras != null&& paras.size() >0)
arguments =encodeArgs(paras);
// Append the arguments tothe query string if GET.
if(method.equalsIgnoreCase("get") &&arguments != null)
url = url +"?" + arguments;
// Create the URL and openthe connection.
try {
requestUrl =new URL(url);
con =requestUrl.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
if(method.equalsIgnoreCase("post")) {
con.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
con.setDoInput(true);
}
//为请求添加“头”,即请求的header,property:
if (headers!= null && headers.size()> 0) {
Set<String> headerSet =headers.keySet();
Iterator<String> i =headerSet.iterator();
while (i.hasNext()) {
String headerName = i.next();
String headerValue = (String)headers.get(headerName);
con.setRequestProperty(headerName, headerValue);
}
}
//先把“附加信息”传到”服务器“:
if(method.equalsIgnoreCase("post")) {
DataOutputStream out = new DataOutputStream(con
.getOutputStream());
out.writeBytes(arguments);
out.flush();
out.close();
}
//向服务器发送请求:
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
con.getOutputStream();
//从“连接”里面获得一个流向“服务器”的“输出流”:
OutputStream outStream = con.getOutputStream();
//将“字节输出流”拼装成“字符输出流”:
PrintWriter out = new PrintWriter(outStream);
//向“字符输入流”写入信息到“服务器”:
out.print(xmlData);
//刷新流,将“缓冲区”中的残留数据全部写到“服务器”:
out.flush();
//关闭向“服务器”的输出流,等待服务器的返回:
out.close();
//获得“服务器”返回的“输入流”,即服务器的返回数据流:
in =con.getInputStream();
} catch (Exception e) {
System.out.println("**********************************************\n"+
"*程序员提示:与服务器的“连接出现问题!");
e.printStackTrace();
}
return in;
}
//自己制作的“工具方法”,用于将“附加信息”拼接成一个完整的“字符串”;
@SuppressWarnings("deprecation")
private String encodeArgs(HashMap<String,String> args) {
if(args==null){
return"";
}
StringBuffer buf = newStringBuffer();
Set<String> names =args.keySet();
Iterator<String> i =names.iterator();
while (i.hasNext()) {
String name= i.next();
String value= args.get(name);
buf.append(URLEncoder.encode(name));
buf.append("=");
buf.append(URLEncoder.encode(value));
if(i.hasNext())
buf.append("&");
}
return buf.toString();
}
}
1:> URL请求的类别:
分为二类,GET与POST请求。二者的区别在于:
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
2:> URLConnection的对象问题:
URLConnection的对象,如下代码示例:
//下面的index.jsp由<servlet-mapping>映射到
// 一个Servlet(com.quantanetwork.getClientDataServlet)
// 该Servlet的注意点下边会提到
URL url =
new
URL( " http://localhost:8080/TestHttpURLConnectionPro/index.jsp" );
URLConnection rulConnection =
url.openConnection();//
此处的urlConnection对象实际上是根据URL的
//
请求协议(此处是http)生成的URLConnection类
//
的子类HttpURLConnection,故此处最好将其转化
//
为HttpURLConnection类型的对象,以便用到
//
HttpURLConnection更多的API.如下:
HttpURLConnection httpUrlConnection =
(HttpURLConnection) rulConnection;
3:> HttpURLConnection对象参数问题
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
//
http正文内,因此需要设为true, 默认情况下是false;
httpUrlConnection.setDoOutput(true
);
//
设置是否从httpUrlConnection读入,默认情况下是true;
httpUrlConnection.setDoInput(true
);
//
Post 请求不能使用缓存
httpUrlConnection.setUseCaches(false
);
//
设定传送的内容类型是可序列化的java对象
//
(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
httpUrlConnection.setRequestProperty("
Content-type "
, "
application/x-java-serialized-object"
);
//
设定请求的方法为"POST",默认是GET
httpUrlConnection.setRequestMethod("
POST ");
//
连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成,
httpUrlConnection.connect();
4:> HttpURLConnection连接问题:
// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,
//
所以在开发中不调用上述的connect()也可以)。
OutputStream outStrm =
httpUrlConnection.getOutputStream();
5:> HttpURLConnection写数据与发送数据问题:
// 现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。
ObjectOutputStream objOutputStrm =
new
ObjectOutputStream(outStrm);
//
向对象输出流写出数据,这些数据将存到内存缓冲区中
objOutputStrm.writeObject(new
String( "
我是测试数据 "
));
//
刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)
objOutputStm.flush();
//
关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,
//
在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
objOutputStm.close();
//
调用HttpURLConnection连接对象的getInputStream()函数,
//
将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
InputStream inStrm =
httpConn.getInputStream(); //
<===注意,实际发送请求的代码段就在这里
//
上边的httpConn.getInputStream()方法已调用,本次HTTP请求已结束,下边向对象输出流的输出已无意义,
//
既使对象输出流没有调用close()方法,下边的操作也不会向对象输出流写入任何数据.
//
因此,要重新发送数据时需要重新创建连接、重新设参数、重新创建流对象、重新写数据、
//
重新发送数据(至于是否不用重新这些操作需要再研究)
objOutputStm.writeObject(new
String( ""
));
httpConn.getInputStream();
总结:a:)HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
无论是post还是get,http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
b:) 在用POST方式发送URL请求时,URL请求参数的设定顺序是重中之重,
对connection对象的一切配置(那一堆set函数)
都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。
这些顺序实际上是由http请求的格式决定的。
如果inputStream读操作在outputStream的写操作之前,会抛出例外:
java.net.ProtocolException: Cannot write output after readinginput.......
c:) http请求实际上由两部分组成,
一个是http头,所有关于此次http请求的配置都在http头里面定义,
一个是正文content。
connect()函数会根据HttpURLConnection对象的配置值生成http头部信息,因此在调用connect函数之前,
就必须把所有的配置准备好。
d:) 在http头后面紧跟着的是http请求的正文,正文的内容是通过outputStream流写入的,
实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,
而是存在于内存缓冲区中,待outputStream流关闭时,根据输入的内容生成http正文。
至此,http请求的东西已经全部准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求
正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http
请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数
之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)
都是没有意义的了,执行这些操作会导致异常的发生。
6:> Servlet端的开发注意点:
a:) 对于客户端发送的POST类型的HTTP请求,Servlet必须实现doPost方法,而不能用doGet方法。
b:)用HttpServletRequest的getInputStream()方法取得InputStream的对象,比如:
InputStream inStream = httpRequest.getInputStream();
现在调用inStream.available()(该方法用于“返回此输入流下一个方法调用可以不受阻塞地
从此输入流读取(或跳过)的估计字节数”)时,永远都反回0。试图使用此方法的返回值分配缓冲区,
以保存此流所有数据的做法是不正确的。那么,现在的解决办法是
Servlet这一端用如下实现:
InputStream inStream = httpRequest.getInputStream();
ObjectInputStream objInStream = newObjectInputStream(inStream);
Object obj = objInStream.readObject();
// 做后续的处理
// 。。。。。。
// 。。。 。。。
而客户端,无论是否发送实际数据都要写入一个对象(那怕这个对象不用),如:
ObjectOutputStream objOutputStrm = newObjectOutputStream(outStrm);
objOutputStrm.writeObject(new String("")); // 这里发送一个空数据
// 甚至可以发一个null对象,服务端取到后再做判断处理。
objOutputStrm.writeObject(null);
objOutputStrm.flush();
objOutputStrm.close();
注意:上述在创建对象输出流ObjectOutputStream时,如果将从HttpServletRequest取得的输入流
(即:newObjectOutputStream(outStrm)中的outStrm)包装在BufferedOutputStream流里面,
则必须有objOutputStrm.flush();这一句,以便将流信息刷入缓冲输出流.如下:
ObjectOutputStream objOutputStrm = new ObjectOutputStream(newBufferedOutputStream(outStrm));
objOutputStrm.writeObject(null);
objOutputStrm.flush(); // <======此处必须要有.
objOutputStrm.close();
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout",超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout",超时毫秒数字符串);
其中:sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)
例如:
System.setProperty("sun.net.client.defaultConnectTimeout","30000");
System.setProperty("sun.net.client.defaultReadTime
Java中可以使用HttpURLConnection来请求WEB资源。
HttpURLConnection对象不能直接构造,需要通过URL.openConnection()来获得HttpURLConnection对象,示例代码如下:
String szUrl =
" http://www.ee2ee.com/ "
;
URL url
=
new URL(szUrl);
HttpURLConnection urlCon =
(HttpURLConnection)url.openConnection();
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout",超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout",超时毫秒数字符串);
其中:sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)
例如:
System.setProperty("sun.net.client.defaultConnectTimeout","30000");
System.setProperty("sun.net.client.defaultReadTimeout","30000");
JDK1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法:
setConnectTimeout:设置连接主机超时(单位:毫秒)
setReadTimeout:设置从主机读取数据超时(单位:毫秒)
例如:
HttpURLConnection urlCon =
(HttpURLConnection)url.openConnection();
urlCon.setConnectTimeout(
30000 );
urlCon.setReadTimeout(
30000 );
需要注意的是,笔者在JDK1.4.2环境下,发现在设置了defaultReadTimeout的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求,出现一次请求调用,请求服务器两次的问题(Trouble)。我认为这是JDK1.4.2的一个bug。在JDK1.5.0中,此问题已得到解决,不存在自动重发现象。out","30000");
==================================================================================================
最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。
下面的代码简单描述了如何使用HttpURLConnection发起这两种请求,以及传递参数的方法:
public class HttpInvoker ...{
publicstatic final String GET_URL = "http://localhost:8080/welcome1";
publicstatic final String POST_URL = "http://localhost:8080/welcome1";
publicstatic void readContentFromGet() throws IOException ...{
// 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
String getURL = GET_URL + "?username="
+ URLEncoder.encode("fat man", "utf-8");
URL getUrl = new URL(getURL);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
//返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
// 进行连接,但是实际上getrequest要在下一句的connection.getInputStream()函数中才会真正发到
// 服务器
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
System.out.println("=============================");
System.out.println("Contents of get request");
System.out.println("=============================");
String lines;
while ((lines = reader.readLine()) != null) ...{
System.out.println(lines);
}
reader.close();
// 断开连接
connection.disconnect();
System.out.println("=============================");
System.out.println("Contents of get request ends");
System.out.println("=============================");
}
publicstatic void readContentFromPost() throws IOException ...{
// Post请求的url,与get不同的是不需要带参数
URL postUrl = new URL(POST_URL);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post cannot use caches
// Post 请求不能使用缓存
connection.setUseCaches(false);
// This method takes effects to
// every instances of this class.
//URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
//意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// The URL-encoded contend
// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
String content = "firstname=" + URLEncoder.encode("一个大肥人","utf-8");
//DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(content);
out.flush();
out.close(); // flush and close
BufferedReader reader = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
String line;
System.out.println("=============================");
System.out.println("Contents of post request");
System.out.println("=============================");
while ((line = reader.readLine()) != null) ...{
System.out.println(line);
}
System.out.println("=============================");
System.out.println("Contents of post request ends");
System.out.println("=============================");
reader.close();
connection.disconnect();
}
publicstatic void main(String[] args) ...{
// TODO Auto-generated method stub
try ...{
readContentFromGet();
readContentFromPost();
} catch (IOException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上面的readContentFromGet()函数产生了一个get请求,传给servlet一个username参数,值为"fatman"。
readContentFromPost()函数产生了一个post请求,传给servlet一个firstname参数,值为"一个大肥人"。
HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到HttpURLConnection.getInputStream()这个函数里面才正式发送出去。
在readContentFromPost()中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。
http请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。
紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。
至此,http请求的东西已经准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。
本节深入学习post请求。
上节说道,post请求的OutputStream实际上不是网络流,而是写入内存,在getInputStream中才真正把写道流里面的内容作为正文与根据之前的配置生成的httprequest头合并成真正的http request,并在此时才真正向服务器发送。
HttpURLConnection.setChunkedStreamingMode函数可以改变这个模式,设置了ChunkedStreamingMode后,不再等待OutputStream关闭后生成完整的httprequest一次过发送,而是先发送httprequest头,正文内容则是网路流的方式实时传送到服务器。实际上是不告诉服务器http正文的长度,这种模式适用于向服务器传送较大的或者是不容易获取长度的数据,如文件。下面以一段代码讲解一下,请与Http学习之使用HttpURLConnection发送post和get请求中的readContentFromPost()函数作对比:
publicstatic void readContentFromChunkedPost() throws IOException...{
URL postUrl = new URL(POST_URL);
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setChunkedStreamingMode(5);
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
String content = "firstname=" +URLEncoder.encode("一个大肥人 "
+
" "
+
"asdfasfdasfasdfaasdfasdfasdfdasfs", "utf-8");
out.writeBytes(content);
out.flush();
out.close(); // 到此时服务器已经收到了完整的httprequest了,而在readContentFromPost()函数里,要等到下一句服务器才能收到http请求。
BufferedReader reader = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
out.flush();
out.close(); // flush and close
String line;
System.out.println("=============================");
System.out.println("Contents of post request");
System.out.println("=============================");
while ((line = reader.readLine()) != null) ...{
System.out.println(line);
}
System.out.println("=============================");
System.out.println("Contents of post request ends");
System.out.println("=============================");
reader.close();
connection.disconnect();
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dodolzg/archive/2010/10/20/5954191.aspx
=============================================================================================
*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.superMail.action.myFocus;
//import java.io.BufferedReader;
import java.io.DataOutputStream;
//import java.io.IOException;
import java.io.InputStream;
//import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
//import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
//import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
//import org.w3c.dom.Text;
//import org.xml.sax.SAXException;
public class Test2 extends Action {
List obj=newArrayList(0);
@SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
public ActionForward execute(ActionMapping mapping, ActionFormform,
HttpServletRequest request, HttpServletResponse response) {
String url="http://218.204.254.218:8080/richlifeApp/share/pc_getWholeCatalog";
StringxmlData="<?xml version='1.0' encoding='UTF-8'standalone='no' ?>"
+"<getWholeCatalogownerMSISDN="15989202763"/>";
String method="GET";
String auth="BasicMTU5ODkyMDI3NjM6U1QtMTQ2NzMtVVZUbTVMVVVRWlpOQUxkQVVrWlBGM21XbWdvcFhDVG5IUFEtMjBfXzE=";
HashMap paras=newHashMap();
HashMap heads=newHashMap();
//Vector m_vec=newVector();
heads.put("pragma","no-cache");
heads.put("Accept-Language","UTF-8");
heads.put("Authorization",auth);
//向服务器发送消息,并获得返回的“输入流”:
InputStreamin=getInput(url,xmlData,method,paras,heads);
//以下用于测试:
//为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db =null;
try {
db =dbf.newDocumentBuilder();
} catch(ParserConfigurationException pce) {
System.err.println(pce); // 出异常时输出异常信息,然后退出,下同
System.exit(1);
}
Document doc = null;
try {
System.out.println("开始解析XML结构体:");
doc =db.parse(in);
} catch (Exception e) {
e.printStackTrace();
}
//下面是解析XML的全过程,比较简单,先取根元素"学生花名册"
Element result =doc.getDocumentElement();
// 取"学生"元素列表
NodeList catalogNodes =result.getElementsByTagName_r("catalogNode");
System.out.println(catalogNodes.getLength());
for (int i = 0; i< catalogNodes.getLength(); i++) {
//依次取每个"学生"元素
ElementcatalogNode = (Element) catalogNodes.item(i);
StringcatalogName=catalogNode.getAttribute("catalogName");
StringisShared=catalogNode.getAttribute("isShared");
//打印出节点的“属性值”:
System.out.println("catalogName :"+catalogName);
System.out.println("isShared:"+isShared);
MyFoldermf=new MyFolder(catalogName,isShared);
//把获得的值放到缓存里面:
obj.add(mf);
}
HttpSessionsen=request.getSession();
sen.setAttribute("obj",obj);
returnmapping.findForward("ReturnJspMap");
}
@SuppressWarnings("unchecked")
private InputStream getInput(String url,String xmlData,
Stringmethod,HashMap paras,HashMap headers){
//用来放“从服务器收到的‘输入流’”:
InputStream in = null;
String arguments = null;
//用来向“服务器”发送请求时,服务器的“地址”:
URL requestUrl=null;
//与服务建立“连接”后,获得的“连接”的“对象”,
//包含与“服务器”相关的各种“连接,流,资源:
URLConnection con=null;
if (url == null){
System.out.println("请求的服务器路径为 null !");
}
//加上“请求”的附加数据:比如?user=lijun&pwd=lijun
if (paras != null&& paras.size() >0)
arguments =encodeArgs(paras);
// Append the arguments tothe query string if GET.
if(method.equalsIgnoreCase("get") &&arguments != null)
url = url +"?" + arguments;
// Create the URL and openthe connection.
try {
requestUrl =new URL(url);
con =requestUrl.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
if(method.equalsIgnoreCase("post")) {
con.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
con.setDoInput(true);
}
//为请求添加“头”,即请求的header,property:
if (headers!= null && headers.size()> 0) {
Set<String> headerSet =headers.keySet();
Iterator<String> i =headerSet.iterator();
while (i.hasNext()) {
String headerName = i.next();
String headerValue = (String)headers.get(headerName);
con.setRequestProperty(headerName, headerValue);
}
}
//先把“附加信息”传到”服务器“:
if(method.equalsIgnoreCase("post")) {
DataOutputStream out = new DataOutputStream(con
.getOutputStream());
out.writeBytes(arguments);
out.flush();
out.close();
}
//向服务器发送请求:
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
con.getOutputStream();
//从“连接”里面获得一个流向“服务器”的“输出流”:
OutputStream outStream = con.getOutputStream();
//将“字节输出流”拼装成“字符输出流”:
PrintWriter out = new PrintWriter(outStream);
//向“字符输入流”写入信息到“服务器”:
out.print(xmlData);
//刷新流,将“缓冲区”中的残留数据全部写到“服务器”:
out.flush();
//关闭向“服务器”的输出流,等待服务器的返回:
out.close();
//获得“服务器”返回的“输入流”,即服务器的返回数据流:
in =con.getInputStream();
} catch (Exception e) {
System.out.println("**********************************************\n"+
"*程序员提示:与服务器的“连接出现问题!");
e.printStackTrace();
}
return in;
}
//自己制作的“工具方法”,用于将“附加信息”拼接成一个完整的“字符串”;
@SuppressWarnings("deprecation")
private String encodeArgs(HashMap<String,String> args) {
if(args==null){
return"";
}
StringBuffer buf = newStringBuffer();
Set<String> names =args.keySet();
Iterator<String> i =names.iterator();
while (i.hasNext()) {
String name= i.next();
String value= args.get(name);
buf.append(URLEncoder.encode(name));
buf.append("=");
buf.append(URLEncoder.encode(value));
if(i.hasNext())
buf.append("&");
}
return buf.toString();
}
}
相关文章推荐
- 使用HttpURLConnection向服务器发送post和get请求
- Android使用HttpUrlConnection请求服务器发送数据详解
- Android使用HttpUrlConnection请求服务器发送数据详解
- Android使用HttpUrlConnection请求服务器发送数据详解
- 在Java中使用HttpURLConnection发送http客户端请求、服务器端返回信息、接受服务器端的信息
- 使用HttpURLConnection向服务器发送post和get请求(转)
- 使用HttpURLConnection向服务器发送post和get请求
- 使用HttpURLConnection向服务器发送post和get请求
- 使用HttpURLConnection向服务器发送post和get请求
- 使用HttpURLConnection向服务器发送get请求
- 使用HttpURLConnection向服务器发送post请求
- IT忍者神龟之使用HttpURLConnection向服务器发送post和get请求
- Android使用HttpUrlConnection请求服务器发送数据详解
- 通过HttpURLConnection连接服务器,发送报文,获取服务器报文返回
- android发送http请求—-URLConnection、HttpURLConnection的使用
- Http学习之使用HttpURLConnection发送post请求深入 .
- HttpURLConnection 向服务器发送post和get请求 并接收响应
- Android使用HttpURLConnection进行POST请求,向服务器上传数据
- Android--使用Http向服务器发送请求并取得返回结果,下载图片
- Http学习之使用HttpURLConnection发送post和get请求(3)