HttpURLConnection的get和post处理方法(含图片)
来源:互联网 发布:js 添加div classname 编辑:程序博客网 时间:2024/05/22 04:24
原文地址http://blog.csdn.net/arsenic/article/details/8120581
通用方法GET和POST
- package com.dong.test.binaryimage;
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class TestHttpPost {
- private static String PATH = "http://localhost:8080/TestWeb/servlet/HelloServer";
- private static URL url;
- public TestHttpPost() {
- // TODO Auto-generated constructor stub
- }
- static {
- try {
- url = new URL(PATH);
- } catch (MalformedURLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- Map<String, String> map = new HashMap<String, String>();
- map.put("name", "xiaowang");
- map.put("age", "29");
- System.out.println(sendPostMessage(map, "UTF-8"));
- System.out.println(sendGet(PATH,"name=xiaowang"));
- }
- public static String sendGet(String url, String param)
- {
- String result = "";
- BufferedReader in = null;
- try
- {
- String urlName = url + "?" + param;
- URL realUrl = new URL(urlName);
- // 打开和URL之间的连接
- URLConnection conn = realUrl.openConnection();
- // 设置通用的请求属性
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestProperty("user-agent",
- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
- // 建立实际的连接
- conn.connect();
- // 获取所有响应头字段
- Map<String, List<String>> map = conn.getHeaderFields();
- // 遍历所有的响应头字段
- for (String key : map.keySet())
- {
- System.out.println(key + "--->" + map.get(key));
- }
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(
- new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null)
- {
- result += "\n" + line;
- }
- }
- catch (Exception e)
- {
- System.out.println("发送GET请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输入流
- finally
- {
- try
- {
- if (in != null)
- {
- in.close();
- }
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- }
- return result;
- }
- public static String sendPostMessage(Map<String, String> params,
- String encode) {
- // 作为StringBuffer初始化的字符串
- StringBuffer buffer = new StringBuffer();
- try {
- if (params != null && !params.isEmpty()) {
- for (Map.Entry<String, String> entry : params.entrySet()) {
- // 完成转码操作
- buffer.append(entry.getKey()).append("=").append(
- URLEncoder.encode(entry.getValue(), encode))
- .append("&");
- }
- buffer.deleteCharAt(buffer.length() - 1);
- }
- // System.out.println(buffer.toString());
- // 删除掉最有一个&
- System.out.println("-->>" + buffer.toString());
- HttpURLConnection urlConnection = (HttpURLConnection) url
- .openConnection();
- urlConnection.setConnectTimeout(3000);
- urlConnection.setRequestMethod("POST");
- urlConnection.setDoInput(true);// 表示从服务器获取数据
- urlConnection.setDoOutput(true);// 表示向服务器写数据
- // 获得上传信息的字节大小以及长度
- byte[] mydata = buffer.toString().getBytes();
- // 表示设置请求体的类型是文本类型
- urlConnection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- urlConnection.setRequestProperty("Content-Length", String
- .valueOf(mydata.length));
- // 获得输出流,向服务器输出数据
- OutputStream outputStream = urlConnection.getOutputStream();
- outputStream.write(mydata, 0, mydata.length);
- outputStream.close();
- // 获得服务器响应的结果和状态码
- int responseCode = urlConnection.getResponseCode();
- if (responseCode == 200) {
- 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 "";
- }
- 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 = "";
- if (inputStream != null) {
- try {
- 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;
- }
- }
GET处理方法
- package com.http.get;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import org.apache.http.message.BasicNameValuePair;
- public class HttpUtils {
- private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png";
- public HttpUtils() {
- // TODO Auto-generated constructor stub
- }
- public static void saveImageToDisk() {
- InputStream inputStream = getInputStream();
- byte[] data = new byte[1024];
- int len = 0;
- FileOutputStream fileOutputStream = null;
- try {
- fileOutputStream = new FileOutputStream("C:\\test.png");
- while ((len = inputStream.read(data)) != -1) {
- fileOutputStream.write(data, 0, len);
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } 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();
- }
- }
- }
- }
- /**
- * 获得服务器端的数据,以InputStream形式返回
- * @return
- */
- public static InputStream getInputStream() {
- InputStream inputStream = null;
- HttpURLConnection httpURLConnection = null;
- try {
- URL url = new URL(URL_PATH);
- if (url != null) {
- httpURLConnection = (HttpURLConnection) url.openConnection();
- // 设置连接网络的超时时间
- httpURLConnection.setConnectTimeout(3000);
- httpURLConnection.setDoInput(true);
- // 表示设置本次http请求使用GET方式请求
- httpURLConnection.setRequestMethod("GET");
- int responseCode = httpURLConnection.getResponseCode();
- if (responseCode == 200) {
- // 从服务器获得一个输入流
- 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 main(String[] args) {
- // 从服务器获得图片保存到本地
- saveImageToDisk();
- }
- }
POST
- package com.http.post;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.Map;
- public class HttpUtils {
- // 请求服务器端的url
- private static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";
- private static URL url;
- public HttpUtils() {
- // TODO Auto-generated constructor stub
- }
- static {
- try {
- url = new 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 buffer = new StringBuffer();
- try {
- if (params != null && !params.isEmpty()) {
- for (Map.Entry<String, String> entry : params.entrySet()) {
- // 完成转码操作
- buffer.append(entry.getKey()).append("=").append(
- URLEncoder.encode(entry.getValue(), encode))
- .append("&");
- }
- buffer.deleteCharAt(buffer.length() - 1);
- }
- // System.out.println(buffer.toString());
- // 删除掉最有一个&
- System.out.println("-->>"+buffer.toString());
- HttpURLConnection urlConnection = (HttpURLConnection) url
- .openConnection();
- urlConnection.setConnectTimeout(3000);
- urlConnection.setRequestMethod("POST");
- urlConnection.setDoInput(true);// 表示从服务器获取数据
- urlConnection.setDoOutput(true);// 表示向服务器写数据
- // 获得上传信息的字节大小以及长度
- byte[] mydata = buffer.toString().getBytes();
- // 表示设置请求体的类型是文本类型
- urlConnection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- urlConnection.setRequestProperty("Content-Length",
- String.valueOf(mydata.length));
- // 获得输出流,向服务器输出数据
- OutputStream outputStream = urlConnection.getOutputStream();
- outputStream.write(mydata,0,mydata.length);
- outputStream.close();
- // 获得服务器响应的结果和状态码
- int responseCode = urlConnection.getResponseCode();
- if (responseCode == 200) {
- 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 = "";
- if (inputStream != null) {
- try {
- 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;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Map<String, String> params = new HashMap<String, String>();
- params.put("username", "admin");
- params.put("password", "1234");
- String result = HttpUtils.sendPostMessage(params, "utf-8");
- System.out.println("--result->>" + result);
- }
- }
- package com.http.post;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- 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;
- public class HttpUtils {
- public HttpUtils() {
- // TODO Auto-generated constructor stub
- }
- public static String sendHttpClientPost(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);
- // 使用Post方式提交数据
- HttpPost httpPost = new HttpPost(path);
- httpPost.setEntity(entity);
- // 指定post请求
- DefaultHttpClient client = new DefaultHttpClient();
- HttpResponse httpResponse = client.execute(httpPost);
- if (httpResponse.getStatusLine().getStatusCode() == 200) {
- 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
- */
- public 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 = "";
- if (inputStream != null) {
- try {
- 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;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";
- Map<String, String> params = new HashMap<String, String>();
- params.put("username", "admin");
- params.put("password", "123");
- String result = HttpUtils.sendHttpClientPost(path, params, "utf-8");
- System.out.println("-->>"+result);
- }
- }
0 0
- HttpURLConnection的get和post处理方法(含图片)
- HttpURLConnection的get和post处理方法(含图片)
- HttpURLConnection的post和Get方法
- HttpUrlConnection的get和post请求方法
- 网络请求----HttpURLConnection的get,post和图片加载
- Android HttpUrlConnection 的“POST”和"GET"方法学习心得
- HttpURLConnection 访问服务器,GET和POST方法.
- 安卓中HttpUrlConnection get和post请求方法
- httpclient的post和get,httpurlconnection的post和get
- HttpUrlConnection 下的post, get , 和图片下载(工具类)
- HttpURLConnection的get和post请求
- HttpUrlConnection的GET请求和POST请求
- HttpURLConnection的GET和POST请求
- HttpURLConnection的GET和POST用法
- android的HttpURLConnection实现post和get
- HttpURLConnection的get和post请求实例
- httpurlconnection的Get请求和Post请求
- HttpURLConnection的GET和POST请求方式
- 终于不用再苦逼地写文档了!一步步教你如何生成可调试的API
- bestcoder+置换群组成的各自环后减一累加
- HDOJ 5366 The mook jong(规律)
- Linux编程学习之路_1
- PHP
- HttpURLConnection的get和post处理方法(含图片)
- 例题 8-2 和为0的4个值 UVa 1152
- 让Ubuntu更多的使用物理内存
- 浮点型JAVA008
- 【Scala学习笔记】1. Hello Scala
- c++ vector实验
- 二维码扫描-zbar的使用
- 【java】面向对象综述
- Web_JavaScript_JS循环滚动效果;