HTTP访问协议封装

此封装类可以直接调用接口

package com.google.zxing.client.android.util;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;


public class HttpUtil {
//声明Based URL常量
//public static final String BASE_URL="http://192.168.1.125:8080";

//服务端的

//public static final String BASE_URL="http://www.bai.cn";

//通过URL获取HttpGet对象
public static HttpGet getHttpGet(String url){
//实例化HttpGet
HttpGet request = new HttpGet(url);
return request;
}

//通过URL获取HttpPost对象
public static HttpPost getHttpPost(String url){
HttpPost request = new HttpPost(url);
return request;
}
//通过HttpGet获得HttpResponse对象
public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException, IOException{
HttpResponse response= new DefaultHttpClient().execute(request);
return response;
}
//通过HttpPost获得HttpResponse对象
public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException, IOException{
HttpResponse response = new DefaultHttpClient().execute(request);
return response;
}

/**
* 通过URL发送post请求,返回请求结果
*/
public static String queryStringForPost(String url){
//获得HttpPost实例
HttpPost request = HttpUtil.getHttpPost(url);
String result = null ;
try {
HttpResponse response =HttpUtil.getHttpResponse(request);
//判断是否请求成功
if(response.getStatusLine().getStatusCode()==200){
//获得返回结果
result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (Exception e) {
e.printStackTrace();
result ="网络异常";
Log.i("Other", "走这里了?");
return result;
}
return null;
}
/**
* 通过HttpPost发送get 请求,返回请求结果
*/
public static String queryStringForGet(String url){
//获得HttpPost实例
HttpGet request = HttpUtil.getHttpGet(url);
String result = null ;
try {
HttpResponse response =HttpUtil.getHttpResponse(request);
//判断是否请求成功
if(response.getStatusLine().getStatusCode()==200){
//获得返回结果
result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (Exception e) {
e.printStackTrace();
result ="网络异常";
return result;
}
return null;
}
/**
* 通过HttpPost发送Post请求,返回请求结果
*/
public static String queryStringForPost(HttpPost request){
String result = null ;
try {
//获取HttpResponse实例
HttpResponse response =HttpUtil.getHttpResponse(request);
//判断是否请求成功
if(response.getStatusLine().getStatusCode()==200){
//获得返回结果
result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (Exception e) {
e.printStackTrace();
result ="网络异常";
Log.i("Other", "123sdfgds");
return result;
}
return null;
}

}

你可能感兴趣的:(http)