HttpURLConnection 在java里面会发生能用,然而在Android里却不能用的情况!
private class MyAuthenticator extends Authenticator { private String user = null; private String passwd = null; public MyAuthenticator(String user, String passwd) { this.user = user; this.passwd = passwd; } @Override public PasswordAuthentication getPasswordAuthentication() { System.out.println("getPasswordAuthentication"); return (new PasswordAuthentication(user, passwd.toCharArray())); } } public String doRequest(String user, String passwd, String link) throws Exception { Authenticator.setDefault(new MyAuthenticator(user, passwd)); URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); InputStream in = new BufferedInputStream(conn.getInputStream()); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(10000); int b; while ((b = in.read()) != -1) { bout.write(b); } return bout.toString(); } finally { in.close(); } } public int doPost(String user, String passwd, String link, String data) throws Exception { Authenticator.setDefault(new MyAuthenticator(user, passwd)); URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("Accept-Charset", "UTF-8"); // conn.setRequestProperty("Host", "11.22.33.44"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", Integer.toString(data.length())); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); // this is were we're adding post data to the request // wr.write(sb.toString()); wr.write(data); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); return responseCode; }
为了避免这样情况出现,可用HttpDefaultClient
public void doGet(){ DefaultHttpClient client = null; try { // Set url URI uri = new URI("http://yourdomain.com/yourpage?yourparamname=yourparamvalue"); client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(uri.getHost(), uri.getPort(),AuthScope.ANY_SCHEME), new UsernamePasswordCredentials("user", "passwd")); // Set timeout client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); HttpGet request = new HttpGet(uri); HttpResponse response = client.execute(request); if(response.getStatusLine().getStatusCode() == 200) { InputStream responseIS = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS)); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } } else { System.out.println("Resource not available"); } } catch (URISyntaxException e) { System.out.println(e.getMessage()); } catch (ClientProtocolException e) { System.out.println(e.getMessage()); } catch (ConnectTimeoutException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if ( client != null ) { client.getConnectionManager().shutdown(); } } } public void doPut(){ DefaultHttpClient client = null; try { // Set url URI uri = new URI("http://yourdomain.com/yourpage?yourparamname=yourparamvalue"); client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(uri.getHost(), uri.getPort(),AuthScope.ANY_SCHEME), new UsernamePasswordCredentials("user", "passwd")); // Set timeout client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); HttpPut httpPut = new HttpPut(uri); StringEntity se = new StringEntity("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); se.setContentEncoding("UTF-8"); httpPut.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPut.setHeader("Connection", "close"); httpPut.setHeader("Accept-Encoding", "identity"); httpPut.setEntity(se); HttpResponse response = client.execute(httpPut); System.out.println(response.getStatusLine().getStatusCode()); if(response.getStatusLine().getStatusCode() == 200) { InputStream responseIS = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS)); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } } else { System.out.println("Resource not available"); } } catch (URISyntaxException e) { System.out.println(e.getMessage()); } catch (ClientProtocolException e) { System.out.println(e.getMessage()); } catch (ConnectTimeoutException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if ( client != null ) { client.getConnectionManager().shutdown(); } } }
相关推荐
Android HttpUrlConnection使用方法 post and get json.
正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是IOException错误,responseCode = -1。一直想不明白,同一个程序我调用了两次,结果有一个链接一直OK,另一个却一直报这个错误。后来发现两个...
调用URL对象的openConnection( )来获取HttpURLConnection对象实例: HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 设置HTTP请求使用的方法:conn.setRequestMethod("GET"); 设置连接超时,...
web端就是一个简单的php页面,已经放在的我的sae albet.sinaapp.com上,直接使用demo中的url就行,当然,也可以把testPost.PHP放在自己的网站,把url改了就行
这个demo是Android使用HttpURLConnection上传图片到服务器
在 Android 中对 HttpURLConnection 的简单使用,仅供参考。
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();// 取得连接 conn.connect(); InputStream is = conn.getInputStream();//取得返回的InputStream bitmap = BitmapFactory....
使用HttpURLConnection实现断点续传
本文并不针对HTTP协议的具体内容,仅探讨android开发中使用HTTP协议访问网络的两种方式——HttpURLConnection和HttpClient 因为需要访问网络,需在AndroidManifest.xml中添加如下权限 <uses android:name=...
本文通过实例代码给大家介绍了Android基于HttpUrlConnection类的文件下载功能,非常不错,具有参考借鉴价值,需要的的朋友参考下吧
利用httpurlconnection加上线程获取网络上图片并在activity中显示
主要为大家详细介绍了Android HttpURLConnection断点下载的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
针对httpURLConnection 的简单封装,简单易用,支持上传下载 用法自已研究吧、
自己写了一个基于httpurlconnection和Asynctask的例子
Android在使用HttpURLConnection时常常遇到无法同时支持3.0和2.X版本的问题,本源码演示了如何用同一个包支持两个版本的问题。
HttpURLConnection和简单的Android服务器交互
这个demo实现了Android网络请求添加header请求参数实例,包括HttpURLConnection,AsyncHttpClient两个大请求类实现方法
实例Demo程序来示范使用HttpURLConnection实现多线程下载。 使用多线程下载文件可以更快完成文件的下载,因为客户端启动多条线程进行下载就意味着服务器也需要为该客户端提供响应的服务。假设服务器同时最多服务100...
Android使用HttpURLConnection访问网络
彻底解决android开发中,使用用HttpUrlConnection与web服务器之间session保持问题