HttpUtil工具类



/**
* 增强型Http辅助类
* @author zhouli
*
*/
public class EnhancedHttpUtil {

private static HttpClient httpClient;
private static final String TAG = "HttpUtil";

/**
* 获得线程安全的HttpClient对象,能够适应多线程环境
* @return
*/
public static synchronized HttpClient getHttpClient() {
if (null == httpClient) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
"UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 1000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);

// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));

// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
httpClient = new DefaultHttpClient(conMgr, params);
}
return httpClient;
}

/**
* 获得Post请求对象
* @param uri 请求地址,也可以带参数
* @param params 如果为null,则不添加由BasicNameValue封装的参数
* @return
*/
public static HttpPost getPost(String uri, List<BasicNameValuePair> params) {
HttpPost post = new HttpPost(uri);
try {
if(params != null) {
post.setEntity(new UrlEncodedFormEntity(params));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return post;
}

/**
* 用户使用的方法
* 功能:从服务器获得字符串
* @param post
* @return
*/
public static String getString(HttpPost post) {

HttpClient httpClient = getHttpClient();
HttpResponse response;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
post.abort();
Log.v(TAG, "响应失败,请求终止.");
return null;
}
Log.v(TAG, "响应成功.");
return EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
return null;
}
}

/**
* 用户使用的方法
* 功能:请求服务器,返回字符串
* @param post post 请求对象
* @param requestLimit 请求失败限制次数
* @return
*/
public static String getString(HttpPost post, int requestLimit) {

if (requestLimit < 1) {
return null;
}
HttpResponse response;
int currCount = 0; // 当前请求次数
String result = null;

while (currCount < requestLimit) {

HttpClient httpClient = getHttpClient();
currCount++;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Log.v(TAG, "响应成功.");
return EntityUtils.toString(response.getEntity());
} else {
post.abort();
Log.v(TAG, "响应失败,请求终止.");
result = "响应失败,请求终止.";
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage());
if (currCount > requestLimit) {
result = "请求失败.";
break;
}
System.out.println("ClientProtocolException");
} catch (IOException e) {
Log.e(TAG, e.getMessage());
if (e instanceof ConnectTimeoutException) {
result = "连接超时.";
} else {
result = "IO异常.";
}
if (currCount > requestLimit) {
break;
}
System.out.println("IOException");
} finally {
System.out.println("finally");
}
}
return result;
}

/**
* 用户使用的方法
* 功能:请求服务器,返回字符串
* @param uri 字符串形式的请求地址
* @param requestLimit 最多允许的请求失败次数
* @return
*/
public static String getString(String uri, int requestLimit) {

if (requestLimit < 1) {
return null;
}
HttpResponse response;
int currCount = 0; // 当前请求次数
String result = null;
HttpPost post = getPost(uri, null);
while (currCount < requestLimit) {

HttpClient httpClient = getHttpClient();
currCount++;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Log.v(TAG, "响应成功.");
return EntityUtils.toString(response.getEntity());
} else {
post.abort();
Log.v(TAG, "响应失败,请求终止.");
result = "响应失败,请求终止.";
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage());
if (currCount > requestLimit) {
result = "请求失败.";
break;
}
System.out.println("ClientProtocolException");
} catch (IOException e) {
//Log.e(TAG, e.getMessage());
if (e instanceof ConnectTimeoutException) {
result = "连接超时.";
} else {
result = "IO异常.";
}
if (currCount > requestLimit) {
break;
}
//System.out.println("IOException");
} finally {
System.out.println("finally");
}
}
return result;
}

/**
* 释放建立http请求占用的资源
*/
public static void shutdown() {
// 释放建立http请求占用的资源
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}



使用范例:
[code]
package com.laili;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.laili.util.HttpUtil;

public class HttpUtilActivity extends Activity {

private Button btn;
private EditText show;
private String uri = "http://10.2.105.76:8080/json/TestJsonServlet";
private List<BasicNameValuePair> params;
private Handler handler;
private String showStr = "";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

params = new ArrayList<BasicNameValuePair>();

handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x01:
show.setText(showStr);
break;
}
}
};

show = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
new Thread(){
public void run() {
params.add(new BasicNameValuePair("username", "zhelong"));
params.add(new BasicNameValuePair("password", "123456"));
HttpPost post = HttpUtil.getPost(uri, params);
showStr += HttpUtil.getString(post,3);
//System.out.println(response);
handler.sendEmptyMessage(0x01);
};
}.start();
}
});
}
}
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
httputil是一个常用的网络请求工具类,用于发送HTTP请求并获取响应。在使用httputil工具类发送请求时,可以通过设置请求的cookie来实现身份验证、会话管理等功能。 要设置cookie,首先需要创建一个HttpClient对象。HttpClient用于发送请求并获取响应。在创建HttpClient对象时,可以通过HttpClientBuilder类来设置一些自定义的配置,包括cookie的相关设置。 1. 创建HttpClient对象: ```java HttpClient httpClient = HttpClientBuilder.create().build(); ``` 2. 创建HttpPost或HttpGet对象,设置请求URL和其他相关参数。 3. 设置cookie: ```java CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("cookie_name", "cookie_value"); cookie.setDomain("example.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); ``` 这里创建了一个CookieStore对象,用于存储cookie。然后创建一个BasicClientCookie对象,设置cookie的名称和值。可以通过setDomain()和setPath()方法设置cookie的域和路径。将cookie添加到cookieStore中。 然后创建一个HttpContext对象,并将cookieStore设置为其属性。将HttpContext对象传递给HttpClient对象的execute()方法,执行请求。 4. 发送请求: ```java HttpResponse response = httpClient.execute(httpPost, httpContext); ``` 通过以上步骤,就可以使用httputil工具类发送带有cookie的HTTP请求了。在发送请求时,服务器将根据提供的cookie进行身份验证或会话管理。 需要注意的是,htttputil工具类的具体使用方式可能会因具体的框架和版本而有所不同,可以根据实际情况进行相应的调整。以上是一个基本的示例,供参考使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值