当前位置:Gxlcms > PHP教程 > 微博开发1客户端的http的get和post封装

微博开发1客户端的http的get和post封装

时间:2021-07-01 10:21:17 帮助过:6人阅读

这篇博客讲的是客户端如何封装Http协议,客户端如何使用post,get方法,是最最核心的代码之一

以下摘自黄石君的《android与PHP开发》

package com.app.demos.util;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.app.demos.base.C;
import android.util.Log;
@SuppressWarnings("rawtypes")
public class AppClient {

// compress strategy
final private static int CS_NONE = 0;
final private static int CS_GZIP = 1;

// logic variables
private String apiUrl;
private HttpParams httpParams;
private HttpClient httpClient;
private int timeoutConnection = 10000;
private int timeoutSocket = 10000;
private int compress = CS_NONE;

// charset default utf8
private String charset = HTTP.UTF_8;

public AppClient (String url) {
initClient(url);
}

public AppClient (String url, String charset, int compress) {
initClient(url);
this.charset = charset; // set charset
this.compress = compress; // set strategy
}

private void initClient (String url) {
// initialize API URL

this.apiUrl = C.api.base + url;

// c.api.base c是自己建的一个类里面

package com.app.demos.base;
public final class C {

////////////////////////////////////////////////////////////////////////////////////////////////
// core settings (important)

public static final class dir {
public static final String base= "/sdcard/demos";
public static final String faces= base + "/faces";
public static final String images= base + "/images";
}

public static final class api {
public static final String base= "http://192.168.1.2:8001";
public static final String index= "/index/index";
public static final String login= "/index/login";
public static final String logout= "/index/logout";
public static final String faceView = "/image/faceView";
public static final String faceList = "/image/faceList";
public static final String blogList= "/blog/blogList";
public static final String blogView= "/blog/blogView";
public static final String blogCreate= "/blog/blogCreate";
public static final String commentList= "/comment/commentList";
public static final String commentCreate= "/comment/commentCreate";
public static final String customerView= "/customer/customerView";
public static final String customerEdit= "/customer/customerEdit";
public static final String fansAdd= "/customer/fansAdd";
public static final String fansDel= "/customer/fansDel";
public static final String notice= "/notify/notice";
}

public static final class task {
public static final int index= 1001;
public static final int login= 1002;
public static final int logout= 1003;
public static final int faceView= 1004;
public static final int faceList= 1005;
public static final int blogList= 1006;
public static final int blogView= 1007;
public static final int blogCreate= 1008;
public static final int commentList= 1009;
public static final int commentCreate= 1010;
public static final int customerView= 1011;
public static final int customerEdit= 1012;
public static final int fansAdd= 1013;
public static final int fansDel= 1014;
public static final int notice= 1015;
}

public static final class err {
public static final String network= "网络错误";
public static final String message= "消息错误";
public static final String jsonFormat= "消息格式错误";
}

////////////////////////////////////////////////////////////////////////////////////////////////
// intent & action settings

public static final class intent {
public static final class action {
public static final String EDITTEXT= "com.app.demos.EDITTEXT";
public static final String EDITBLOG= "com.app.demos.EDITBLOG";
}
}

public static final class action {
public static final class edittext {
public static final int CONFIG= 2001;
public static final int COMMENT= 2002;
}
}

////////////////////////////////////////////////////////////////////////////////////////////////
// additional settings

public static final class web {
public static final String base= "http://192.168.1.2:8002";
public static final String index= base + "/index.php";
public static final String gomap= base + "/gomap.php";
}
}

String apiSid = AppUtil.getSessionId(); //AppUtil是自己编写的工具类里面封装了一些基本用法比如获取用户session,加密,gzip压缩等等后面介绍
if (apiSid != null && apiSid.length() > 0) {
this.apiUrl += "?sid=" + apiSid;
}
// set client timeout
httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
// init client

httpClient = new DefaultHttpClient(httpParams);

//此处是简单的获取Httpclient

}

public void useWap () { //此处是选择wap的上网方式
HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}

public String get () throws Exception { //封装Http的get方法
try {
HttpGet httpGet = headerFilter(new HttpGet(this.apiUrl));
Log.w("AppClient.get.url", this.apiUrl);
// send get request
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String httpResult = resultFilter(httpResponse.getEntity());
Log.w("AppClient.get.result", httpResult);
return httpResult;
} else {
return null;
}
} catch (ConnectTimeoutException e) {
throw new Exception(C.err.network);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public String post (HashMap urlParams) throws Exception {//封装Http的post方法
try {
HttpPost httpPost = headerFilter(new HttpPost(this.apiUrl));
List postParams = new ArrayList();
// get post parameters
Iterator it = urlParams.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
postParams.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
}
// set data charset
if (this.charset != null) {
httpPost.setEntity(new UrlEncodedFormEntity(postParams, this.charset));
} else {
httpPost.setEntity(new UrlEncodedFormEntity(postParams));
}
Log.w("AppClient.post.url", this.apiUrl);
Log.w("AppClient.post.data", postParams.toString());
// send post request
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String httpResult = resultFilter(httpResponse.getEntity());
Log.w("AppClient.post.result", httpResult);
return httpResult;
} else {
return null;
}
} catch (ConnectTimeoutException e) {
throw new Exception(C.err.network);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

private HttpGet headerFilter (HttpGet httpGet) { 处理发送get数据请求,看是否是压缩格式
switch (this.compress) {
case CS_GZIP:
httpGet.addHeader("Accept-Encoding", "gzip");
break;
default :
break;
}
return httpGet;
}

private HttpPost headerFilter (HttpPost httpPost) { 处理发送post数据请求,看是否是压缩格式
switch (this.compress) {
case CS_GZIP:
httpPost.addHeader("Accept-Encoding", "gzip");
break;
default :
break;
}
return httpPost;
}

private String resultFilter(HttpEntity entity){ 处理获得的数据,看是否是压缩格式
String result = null;
try {
switch (this.compress) {
case CS_GZIP:
result = AppUtil.gzipToString(entity);
break;
default :
result = EntityUtils.toString(entity);
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

}

以上就介绍了微博开发1客户端的http的get和post封装,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行