HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.
MoHttp(Mo = More) is an HTTP client based on java.net.URLConnection which supports:
Requires:
Android 2.3 and above. For Java, the minimum requirement is 1.7.
Write less, do more!
You don't need any another library any more,the only thing to do is add the maven dependency or include the jar in your classpath.
latest releases View on Github
<dependency>
<groupId>io.github.xcr1234</groupId>
<artifactId>moHttp</artifactId>
<version>1.2</version>
</dependency>
compile 'io.github.xcr1234:moHttp:1.2'
if you include apache HttpClient in the classpath,mohttp will automatically work with HttpClient.
Requirement:
Httpclient 4.3.2+,file upload requires apache Httpmime.
This program downloads a URL and print its contents as a string.
public static String getUrl(String url) throws IOException, URISyntaxException {
return Http.GET(url).execute().string();
// return Http.GET(url).execute().string("UTF-8");
}
This program posts data to a service.If you use the cookie storage,you must create a Client object first.
Response response = Http.newClient().POST("http://www.layoutit.com/en/login/do")
.param("login[email]","abcd@qq.com")
.param("login[password]","abcd@qq.com")
.execute();
int code = response.statusCode();
if(code == StatusCode.SC_OK){
System.out.println("login failed.");
}
if(code == StatusCode.SC_FOUND){
System.out.println("login success.");
// do some thing else
}
System.out.println(response.string());
just invoke file mthod,file cotent types and content bytes will be written automatically.
File file = new File("C:\\myPicture.png");
Response response = Http.newClient()
.POST("http://chuantu.biz/upload.php")
.param("MAX_FILE_SIZE","200000000")
.file("uploadimg",file)
.execute();
System.out.println(response.string());
request.execute(new HttpCallback() {
@Override
public void complete(Response response) throws IOException {
System.out.println(response.string());
}
@Override
public void failed(Throwable e) {
System.out.println("fail!");
}
@Override
public void cancelled() {
System.out.println("cancelled!");
}
});
cookies are stored in java.net.CookieStore,which is in Client object.
Http.newClient(); //create Client
request.getClient(); //get Client from Request
response.getClient(); //get Client from Response
//get CookieManager and CookieStore.
java.net.CookieManager cookieManager = client.getCookieManager();
java.net.CookieStore cookieStore = client.getCookieStore();
if you are working with apache HttpClient,cookies are no longer stored in java.net.CookieStore, instead of org.apache.http.client.CookieStore
org.apache.http.client.CookieStore cookieStore =
HttpClientExecutor.getInstance().getCookieStore(client);
org.apache.http.client.HttpClient httpClient =
HttpClientExecutor.getInstance().getHttpClient(client);