`
hellobin
  • 浏览: 62895 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Android HttpURLConnection 与 HttpDefaultClient

阅读更多

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();
			}
		}
	}

 

部分参考 http://www.mustdev.com/?p=71&lang=en

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics