二.Android客户端
得到HttpClient代码:
private static DefaultHttpClient getHttpClient() {
DefaultHttpClient httpClient = new DefaultHttpClient();
// 设置 连接超时时间
httpClient.getParams().setParameter(
HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);
// 设置 读数据超时时间
httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
TIMEOUT_SOCKET);
// 设置 字符集
httpClient.getParams().setParameter("http.protocol.content-charset",
UTF_8);
return httpClient;
}
得到HttpPost:
private static HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
// 设置 请求超时时间
httpPost.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
TIMEOUT_SOCKET);
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.addHeader("Accept-Encoding", "gzip");
return httpPost;
}
访问网络代码:
public static InputStream http_post_return_byte(String url,
Map<String, String> params) throws AppException {
DefaultHttpClient httpclient = null;
HttpPost post = null;
HttpResponse response = null;
StringBuilder sb = null;
StringEntity stringEntity = null;
try {
httpclient = getHttpClient();
post = getHttpPost(url);
sb = new StringBuilder();
if (params != null && !params.isEmpty()) {
Logger.d("In http_post the url is get here");
for (Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(),
HTTP.UTF_8)).append("&");
}
sb.deleteCharAt(sb.lastIndexOf("&"));
Logger.d("In http_post the url is " + url + " and params is "
+ sb.toString());
stringEntity = new StringEntity(sb.toString());
stringEntity
.setContentType("application/x-www-form-urlencoded");
post.setEntity(stringEntity);
}
response = httpclient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
Logger.d("statusCode is " + statusCode);
if (statusCode != HttpStatus.SC_OK) {
throw AppException.http(statusCode);
}
InputStream is = response.getEntity().getContent();
Header contentEncoding = response
.getFirstHeader("Content-Encoding");
if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
is = new GZIPInputStream(new BufferedInputStream(is));
}
return is;
} catch (ClientProtocolException e) {
e.printStackTrace();
throw AppException.http(e);
} catch (IOException e) {
e.printStackTrace();
throw AppException.network(e);
} finally {
/*
* if (!post.isAborted()) {
*
* post.abort(); } httpclient = null;
*/
}
}
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11
