模拟Http请求及访问网络和SDCard的权限设置

1  在manifest.xml文件中,application标签前添加:

<uses-permission android:name="android.permission.INTERNET"/>
<!-- 向SDCard写入数据权限 --> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- SDCard中创建与删除文件权限 -->  
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  这一设置可以没有

2  示例

2.1 使用HttpURLConnection

BasicHttpClient.java

public class BasicHttpClient {
	private static final int TIME_OUT = 1000*6;
	private static final String METHOD_POST="POST";
	private static final String METHOD_GET="GET";
	private static final int HTTP_OK = 200;
	
	public String httpGet(String urlStr) {
		URL url = null;
		HttpURLConnection conn = null;
		InputStream inStream = null;
		String response = null;
		
		try {
			url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(TIME_OUT);
			conn.setRequestMethod(METHOD_GET);
			conn.setRequestProperty("accept", "*/*");
			conn.connect();
			int responseCode = conn.getResponseCode();
			if(responseCode == HTTP_OK) {
				inStream = conn.getInputStream();
				response = getResponse(inStream);
			} else {
				response = "返回码:"+responseCode;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		
		return response;
	}
	
	public String httpPost(String urlStr, String params) {
		byte[] data = params.getBytes();
		URL url = null;
		HttpURLConnection conn = null;
		InputStream inStream = null;
		String response = null;
		
		try {
			url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(TIME_OUT);
			conn.setRequestMethod(METHOD_POST);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.connect();
			DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
			outputStream.write(data);
			outputStream.flush();
			outputStream.close();
			int responseCode = conn.getResponseCode();
			if(responseCode == HTTP_OK) {
				inStream = conn.getInputStream();
				response = getResponse(inStream);
			} else {
				response = "返回码:"+responseCode;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		
		return response;
	}
	
	private String getResponse(InputStream inStream) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = -1;
		byte[] buffer = new byte[1024];
		while((len=inStream.read(buffer))!=-1) {
			outputStream.write(buffer, 0, len);
		}
		byte[] data = outputStream.toByteArray();
		return new String(data);
	}
	
}

BasicHttpClientTest.java

public class BasicHttpClientTest extends AndroidTestCase {
	private static final String TAG = "BasicHttpClientTest";
	String urlStr = "http://192.168.1.107:8080/test/test.txt";
	String params = "id=1&name=jiao";
	public void testHttpGet() {
		BasicHttpClient client = new BasicHttpClient();
		String response = client.httpGet(urlStr+"?"+params);
		Log.i(TAG, response);
	}
	public void testHttpPost() {
		BasicHttpClient client = new BasicHttpClient();
		String response = client.httpPost(urlStr, params);
		Log.i(TAG, response);
	}
}

2.2 使用Apache提供的HttpClient

ApacheHttpClient.java

public class ApacheHttpClient {
	
	public String httpGet(String urlStr) {
		String response = null;
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(urlStr);
		HttpResponse httpResponse;
		try {
			httpResponse = httpclient.execute(httpGet);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			if (responseCode == HttpStatus.SC_OK) {
				response = EntityUtils.toString(httpResponse.getEntity());
			} else {
				response = "返回码:" + responseCode;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return response;
	}

	public String httpPost(String urlStr, List<NameValuePair> params) throws Exception {
		String response = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urlStr);
		try {
			httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = httpClient.execute(httppost);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			if (responseCode == HttpStatus.SC_OK) {
				response = EntityUtils.toString(httpResponse.getEntity());
			} else {
				response = "返回码:" + responseCode;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return response;
	}
}

测试代码:

public void testHttpPost() {
		ApacheHttpClient client = new ApacheHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", "1"));
		params.add(new BasicNameValuePair("name", "jiao"));
		String response = null;
		try {
			response = client.httpPost(urlStr, params);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.i(TAG, "##"+response);
	}















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ADreamClusive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值