1 package com.http.get;
2
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.HttpURLConnection;
7 import java.net.MalformedURLException;
8 import java.net.URL;
9
10 public class HttpUtils {
11 private static String URL_PATH = "http://192.168.1.106:8080/green.jpg";
12 /**
13 * @param args
14 */
15 public static void main(String[] args) {
16 // 调用方法获取图片并保存
17 saveImageToDisk();
18 }
19 /**
20 * 通过URL_PATH的地址访问图片并保存到本地
21 */
22 public static void saveImageToDisk()
23 {
24 InputStream inputStream= getInputStream();
25 byte[] data=new byte[1024];
26 int len=0;
27 FileOutputStream fileOutputStream=null;
28 try {
29 //把图片文件保存在本地F盘下
30 fileOutputStream=new FileOutputStream("F:\test.png");
31 while((len=inputStream.read(data))!=-1)
32 {
33 //向本地文件中写入图片流
34 fileOutputStream.write(data,0,len);
35 }
36 } catch (IOException e) {
37 e.printStackTrace();
38 }
39 finally
40 {
41 //最后关闭流
42 if(inputStream!=null)
43 {
44 try {
45 inputStream.close();
46 } catch (IOException e) {
47 e.printStackTrace();
48 }
49 }
50 if(fileOutputStream!=null)
51 {
52 try {
53 fileOutputStream.close();
54 } catch (IOException e) {
55 e.printStackTrace();
56 }
57 }
58 }
59 }
60 /**
61 * 通过URL获取图片
62 * @return URL地址图片的输入流。
63 */
64 public static InputStream getInputStream() {
65 InputStream inputStream = null;
66 HttpURLConnection httpURLConnection = null;
67
68 try {
69 //根据URL地址实例化一个URL对象,用于创建HttpURLConnection对象。
70 URL url = new URL(URL_PATH);
71
72 if (url != null) {
73 //openConnection获得当前URL的连接
74 httpURLConnection = (HttpURLConnection) url.openConnection();
75 //设置3秒的响应超时
76 httpURLConnection.setConnectTimeout(3000);
77 //设置允许输入
78 httpURLConnection.setDoInput(true);
79 //设置为GET方式请求数据
80 httpURLConnection.setRequestMethod("GET");
81 //获取连接响应码,200为成功,如果为其他,均表示有问题
82 int responseCode=httpURLConnection.getResponseCode();
83 if(responseCode==200)
84 {
85 //getInputStream获取服务端返回的数据流。
86 inputStream=httpURLConnection.getInputStream();
87 }
88 }
89
90 } catch (MalformedURLException e) {
91 e.printStackTrace();
92 } catch (IOException e) {
93 e.printStackTrace();
94 }
95 return inputStream;
96 }
97
98 }
POST方式
这个例子通过POST方式访问一个登陆页面,需要输入用户名(username)和密码(password)。虽然这里使用的Java在讲解问题,但是服务端是使用.Net的框架,一个很简单的HTML页面加一个表单传送的一般处理程序,输入为admin+123为登陆成功,这里不累述了。
Java代码:
1 package com.http.post;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.io.UnsupportedEncodingException;
8 import java.net.HttpURLConnection;
9 import java.net.URL;
10 import java.net.URLEncoder;
11 import java.util.HashMap;
12 import java.util.Map;
13
14 public class postUtils {
15
16 private static String PATH = "http://192.168.222.1:1231/loginas.ashx";
17 private static URL url;
18
19 public postUtils() {
20 }
21 static {
22 try {
23 url = new URL(PATH);
24 } catch (Exception e) {
25 e.printStackTrace();
26 }
27 }
28
29 /**
30 * 通过给定的请求参数和编码格式,获取服务器返回的数据
31 * @param params 请求参数
32 * @param encode 编码格式
33 * @return 获得的字符串
34 */
35 public static String sendPostMessage(Map<String, String> params,
36 String encode) {
37 StringBuffer buffer = new StringBuffer();
38 if (params != null && !params.isEmpty()) {
39 for (Map.Entry<String, String> entry : params.entrySet()) {
40 try {
41 buffer.append(entry.getKey())
42 .append("=")
43 .append(URLEncoder.encode(entry.getValue(), encode))
44 .append("&");//请求的参数之间使用&分割。
45 } catch (UnsupportedEncodingException e) {
46 e.printStackTrace();
47 }
48
49 }
50 buffer.deleteCharAt(buffer.length() - 1);
51 System.out.println(buffer.toString());
52 try {
53 HttpURLConnection urlConnection = (HttpURLConnection) url
54 .openConnection();
55 urlConnection.setConnectTimeout(3000);
56 //设置允许输入输出
57 urlConnection.setDoInput(true);
58 urlConnection.setDoOutput(true);
59 byte[] mydata = buffer.toString().getBytes();
60 //设置请求报文头,设定请求数据类型
61 urlConnection.setRequestProperty("Content-Type",
62 "application/x-www-form-urlencoded");
63 //设置请求数据长度
64 urlConnection.setRequestProperty("Content-Length",
65 String.valueOf(mydata.length));
66 //设置POST方式请求数据
67 urlConnection.setRequestMethod("POST");
68 OutputStream outputStream = urlConnection.getOutputStream();
69 outputStream.write(mydata);
70 int responseCode = urlConnection.getResponseCode();
71 if (responseCode == 200) {
72 return changeInputStream(urlConnection.getInputStream(),
73 encode);
74 }
75 } catch (IOException e) {
76 e.printStackTrace();
77 }
78 }
79 return "";
80 }
81
82 /**
83 * 把服务端返回的输入流转换成字符串格式
84 * @param inputStream 服务器返回的输入流
85 * @param encode 编码格式
86 * @return 解析后的字符串
87 */
88 private static String changeInputStream(InputStream inputStream,
89 String encode) {
90 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
91 byte[] data = new byte[1024];
92 int len = 0;
93 String result="";
94 if (inputStream != null) {
95 try {
96 while ((len = inputStream.read(data)) != -1) {
97 outputStream.write(data,0,len);
98 }
99 result=new String(outputStream.toByteArray(),encode);
100
101 } catch (IOException e) {
102 e.printStackTrace();
103 }
104 }
105 return result;
106 }
107
108 /**
109 * @param args
110 */
111 public static void main(String[] args) {
112 //通过Map设置请求字符串。
113 Map<String, String> params = new HashMap<String, String>();
114 params.put("username", "admin");
115 params.put("password", "123");
116 String result=sendPostMessage(params, "utf-8");
117 System.out.println(result);
118 }
119
120 }
