Androidネットワークツール
3048 ワード
Android開発では、リモートのサーバに接続してデータの読み取りを行う必要があります.Httpプロトコルでサーバから情報を読み出すのが一般的です.以下のコードは、Androidプロジェクトを開発する際に書いた接続ツールで、getとpostの2つのリクエストデータをカプセル化しています.
package com.zhang.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import android.content.Context;
import com.zhang.exception.ExceptionHandle;
import com.zhang.exception.NullPointException;
public class NetUtil {
private HttpClient httpClient = new DefaultHttpClient();
private Context context;
private String charSet = "UTF-8";
public NetUtil(Context context) {
this.context = context;
}
public String sendByGet(String url, List<ParameterEntity> parameters,boolean cacheable) throws ClientProtocolException, IOException {
String result = null;
if(cacheable == true){
//
}else{
if (url != null) {
HttpUriRequest request = new HttpGet(url);
if(parameters != null){
BasicHttpParams params = new BasicHttpParams();
for (ParameterEntity entity : parameters) {
params.setParameter(entity.getKey(), entity.getValue());
}
request.setParams(params);
}
HttpResponse response = httpClient.execute(request);
result = getContent(response);
} else {
ExceptionHandle.handle(context, new NullPointException());
}
}
return result;
}
private String getContent(HttpResponse response) throws IllegalStateException, IOException{
String result = null;
if(response != null){
HttpEntity httpEntity = response.getEntity();
InputStream in = httpEntity.getContent();
InputStreamReader reader = new InputStreamReader(in,charSet);
BufferedReader bread = new BufferedReader(reader);
char[] buf = new char[1024];
StringBuffer buffer = new StringBuffer();
int count = 0;
while((count = bread.read(buf))!= -1){
buffer.append(buf,0,count);
}
result = buffer.toString();
}
return result;
}
public String sendByPost(String url,List<ParameterEntity> parameters, boolean cacheable) throws ClientProtocolException, IOException {
String result = null;
if(cacheable == true){
//
}else{
HttpPost post = new HttpPost(url);
post.setHeader("Accept-Charset", charSet);
if(parameters != null){
BasicHttpParams params = new BasicHttpParams();
for (ParameterEntity entity : parameters) {
params.setParameter(entity.getKey(), entity.getValue());
}
post.setParams(params);
}
HttpResponse response = httpClient.execute(post);
result = getContent(response);
}
return result;
}
}