Weibo Development 1 Client HTTP GET and post encapsulation

Source: Internet
Author: User
Tags php tutorial
This blog is about how the client encapsulates the HTTP protocol, and how the client uses the Post,get method is one of the most core code

The following is an excerpt from Huangshijun's Android and PHP development

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 is a class built by himself.

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= "Network Error";
public static final String message= "Message Error";
public static final String Jsonformat= "bad message format";
}

////////////////////////////////////////////////////////////////////////////////////////////////
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 is a tool class that is written in itself and encapsulates some basic usage, such as getting the user session, encryption, gzip compression, etc.
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);

here is a simple get httpclient

}

public void Usewap () { //Here is the choice of WAP Internet mode
Httphost proxy = new Httphost ("10.0.0.172", "http");
Httpclient.getparams (). Setparameter (Connroutepnames.default_proxy, PROXY);
}

Public String get () throws Exception { //Encapsulate HTTP GET method
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 { //Encapsulating the HTTP POST method
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) { handles sending a Get data request to see if it is a compressed format
Switch (this.compress) {
Case Cs_gzip:
Httpget.addheader ("accept-encoding", "gzip");
Break
Default:
Break
}
return httpget;
}

Private HttpPost Headerfilter (HttpPost httppost) { handles sending post data requests to see if it is a compressed format
Switch (this.compress) {
Case Cs_gzip:
Httppost.addheader ("accept-encoding", "gzip");
Break
Default:
Break
}
return httppost;
}

Private String Resultfilter (httpentity entity) { process the obtained data to see if it is a compressed format
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;
}

}

The above describes the microblogging development 1 client HTTP GET and post package, including the aspects of the content, want to be interested in PHP tutorial friends helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.