今天学习了Http协议编程,以前听过一些,今天又拓宽了一下。
首先,有两种方式:
1.java 接口
2.apache接口
先来演示下java 接口编程:
(1)通过http,get请求从服务器取得数据
public class Java_Get { public static String URL_PATH ="http://192.168.1.104:8080/MyHttp/logo1.jpg" ; /** * 获得服务器端的数据以输入流返回 * @return */ public static InputStream getInputStream(){ InputStream inputStream = null ; try { //创建URL对象 URL url = new URL(URL_PATH); if(url!=null){ //取得HttpsURLConnection连接对象 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection() ; //设置连接网络超时时间,超过3秒自动断开 httpURLConnection.setConnectTimeout(3000) ; //将 doInput 标志设置为 true,指示应用程序要从 URL 连接读取数据。 httpURLConnection.setDoInput(true) ; //将 doOutput 标志设置为 true,指示应用程序要将数据写入 URL 连接。 httpURLConnection.setRequestMethod("GET") ; int responseCode = httpURLConnection.getResponseCode() ; //判断是否正常返回数据 if(responseCode == HttpURLConnection.HTTP_OK){ //从服务器获得输入流 inputStream = httpURLConnection.getInputStream() ; } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return inputStream ; } /** * 将从服务器读到的图片存储在本地 */ public static void saveImage(){ InputStream inputStream = getInputStream() ; byte[] data = new byte[1024] ; FileOutputStream fileOutputStream = null ; int len = 0 ; //图片小于1024个字节 try { fileOutputStream = new FileOutputStream("D:\\ee.jpg") ; while ((len = inputStream.read(data)) != -1) { fileOutputStream.write(data,0,len) ; } } catch (Exception e) { // TODO: handle exception }finally{ if(inputStream!=null){ try { inputStream.close() ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fileOutputStream!=null){ try { fileOutputStream.close() ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void main(String[] args) { //从服务器获取图片保存到本地 saveImage() ; } }
(2)通过http,post从服务器取得数据
public class Java_Post {
private static String URL_PATH = "http://192.168.1.104:8080/MyHttp/LoginServlet";
private static URL url;
// 静态块实例化
static {
try {
url = new URL(URL_PATH);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param params
* 填入url的参数
* @param encode
* 字节编码
* @return
*/
public static String sendPostMessage(Map<String, String> params,
String encode) {
StringBuffer stringBuffer = new StringBuffer();
if (params != null && !params.isEmpty()) {
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer
.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length()-1) ;
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
urlConnection.setConnectTimeout(3000) ;
urlConnection.setDoInput(true) ;
urlConnection.setDoOutput(true) ;
//获得上传信息的字节大小以及长度
byte[] data = stringBuffer.toString().getBytes() ;
//设置请求的类型为文本类型
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") ;
urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length)) ;
OutputStream outputStream = urlConnection.getOutputStream() ;
outputStream.write(data) ;
int responseCode = urlConnection.getResponseCode() ;
if(responseCode == HttpURLConnection.HTTP_OK){
return changeInputStream(urlConnection.getInputStream(),encode) ;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}
/**
* 将读到的流转化为字符串
* @param inputStream
* @param encode
* @return
*/
private static String changeInputStream(InputStream inputStream,String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream() ;
byte[] data = new byte[1024] ;
int len = 0 ;
String result = "" ;
try {
if(inputStream!=null){
while((len = inputStream.read(data))!=-1){
outputStream.write(data, 0, len) ;
}
result = new String(outputStream.toByteArray(),encode) ;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>() ;
map.put("username", "再_见孙悟空") ;
map.put("userpwd", "AMB") ;
String text = sendPostMessage(map,"utf-8");
System.out.println(text);
}
}
2.apache ,post从服务器取得数据
public class Apache_Http { /** * 取得从服务器返回信息 * @param path : 地址 * @param map : 传递的信息 * @param encode : 编码 * @return */ public static String sendHttpPost(String path, Map<String,String> map, String encode) { List<NameValuePair> list = new ArrayList<NameValuePair>() ; if(map!=null && !map.isEmpty()){ for(Map.Entry<String,String> entry : map.entrySet()) list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())) ; } //将请求的参数封装到表单中 try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode) ; HttpPost httpPost = new HttpPost(path) ; httpPost.setEntity(entity) ; DefaultHttpClient client = new DefaultHttpClient() ; HttpResponse httpResponse = client.execute(httpPost) ; if(httpResponse.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK){ return changeInputStream( httpResponse.getEntity().getContent() ,encode);//得到输入流 } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "" ; } /** * 将读到的流转化为字符串 * @param inputStream * @param encode * @return */ private static String changeInputStream(InputStream inputStream,String encode) { // TODO Auto-generated method stub ByteArrayOutputStream outputStream = new ByteArrayOutputStream() ; byte[] data = new byte[1024] ; int len = 0 ; String result = "" ; try { if(inputStream!=null){ while((len = inputStream.read(data))!=-1){ outputStream.write(data, 0, len) ; } result = new String(outputStream.toByteArray(),encode) ; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public static void main(String[] args) { String URL_PATH = "http://192.168.1.104:8080/MyHttp/LoginServlet"; Map<String,String> map = new HashMap<String,String>() ; map.put("username", "再_见孙悟空") ; map.put("userpwd", "AMB") ; String text = sendHttpPost(URL_PATH,map,"utf-8"); System.out.println(text); } }
相关推荐
老罗Android视频开发教程 android之http协议编程代码 很不错的Android开发教程。
HTTP协议编程。基于VC++6.0、可以直接使用
(android之http协议编程)第三集hjava_http_post.zip 关于http协议的post
老罗android视频开发源码和ppt 这是视频配套的源码与PPT, 分了不同的小包 老罗写的, 听说叫罗升阳。
老罗Android开发视频教程源代码,包括入门介绍--常用UI布局介绍--百度地图实战开发--HTTP协议编程
用C#实现HTTP协议下的多线程文件传输
描述了http协议下post提交的方法
用socket 类实现http 客户端应用 Http客户端程序已集成在Java语言中,可以通过URLConnection类调用。遗憾的 是,由于SUN没有公布Http客户程序的源码,它...协议规范,用Java.net.Socket类实现一个HTTP协议客户端程序。
android http协议 网络编程 经典完整代码 非常经典 非常完整的代码.
《C#网络编程高级篇之网页游戏辅助程序设计》涉及的领域包括多线程编程技术、Socket套接字编程、TCP协议编程、HTTP协议编程、远程控制技术、木马技术、模拟键盘和鼠标技术、网页游戏辅助程序设计技术等。
教程名称:老罗Android开发视频教程汇总课程目录:【】android之http协议编程第1集:http协议的介绍【】android之http协议编程第2集:http协议GET方式获取图片【】android之http协议编程第3集:使用Post方式进行提交...
本文首先介绍协议的工作过程,包括协议的一般模型,以及与HTTP协议之间的关系,然后介绍HTTP协议的基本知识,主要介绍在简单服务发现协议中使用的一些协议请求和响应的消息格式。最后详细介绍协议的设备通知和设备...
本书包括TCP \ UDP \ ICMP \ HTTP \ FTP \ POP3 \ SMTP等多种协议的讲解及c#示例代码(VS2005) 本书是学习网络知识和网路通讯协议编程的入门教材 关于RFC部分简略(可以自己去看RFC官网)
调研http协议、TCP协议、UDP协议及socket编程相关知识;根据课程设计要求,选择合适的操作系统、开发环境及测试环境 必需有界面窗口,客户端可以实现网址的录入,协议的选择(TCP或返回信息的显示。服务器端要有...
网络编程是Go语言的一大亮点,课程将教授如何使用Go进行HTTP协议编程,创建RESTful API,并探索WebSocket和TCP/UDP编程。此外,课程还将涵盖测试与调试技巧,包括单元测试、基准测试和代码覆盖率分析,以及如何使用...
网络编程:通过实例学习Go的HTTP协议编程、RESTful API开发、WebSocket通信和TCP/UDP编程。 测试与调试:教授如何编写单元测试,进行基准测试和覆盖率分析,以及使用Go的调试工具。 数据库编程:学习使用Go连接和...
C编程实现http协议
07-http协议、http服务器的实现-1(python和linux高级编程阶段 代码和截图)07-http协议、http服务器的实现-1(python和linux高级编程阶段 代码和截图)07-http协议、http服务器的实现-1(python和linux高级编程阶段...
关于HTTP get post请求,HTTP协议的含义,以及在 IOS里,HTTP协议怎么用