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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中的HttpURLConnection是一个用于发送和接收HTTP请求的类。它是Java标准库中的一部分,并且在Android开发中被广泛使用。 使用HttpURLConnection可以执行以下操作: 1. 创建连接:使用URL对象创建HttpURLConnection对象,并设置连接的URL。 2. 设置请求方法:使用setRequestMethod()方法设置请求的方法,如GET、POST等。 3. 设置请求头:使用setRequestProperty()方法设置请求头信息,如Content-Type、User-Agent等。 4. 设置请求体:对于POST请求,可以使用OutputStream将数据写入请求体。 5. 发送请求:使用connect()方法建立与服务器的连接,并发送请求。 6. 获取响应码:使用getResponseCode()方法获取服务器的响应码。 7. 获取响应数据:根据响应码,可以使用getInputStream()或getErrorStream()方法获取服务器返回的数据流。 8. 解析响应数据:根据服务器返回的数据格式,可以使用相应的解析方式进行解析,如JSON解析、XML解析等。 以下是一个简单的示例代码,演示了如何使用HttpURLConnection发送GET请求并获取响应数据: ```java try { URL url = new URL("http://www.example.com/api/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); // 处理响应数据 String responseData = response.toString(); // ... } else { // 处理错误情况 } } catch (IOException e) { e.printStackTrace(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值