首页 |  个人站点 |  博客园 |  管理 |  返回

Java的HttpClient的实现

HttpClient的概念就是模仿浏览器请求服务端内容,也可以做App和Server之间的链接。

这个是关于Java的HttpClient的简单实例,其实java本身也可以通过自己的net包去做,但是在应用上还是HttpClient方便很多

地址是:http://hc.apache.org/downloads.cgi 
下面是java的实例(这里使用了json的jar包,可以前往http://mvnrepository.com/artifact/org.json/json去寻找下载):

注意:jdk1.8

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class WebSiteRequest {
    public static void main(String args[]) {
        String reqUri = "https://xxx.com";
        String parm = "data=0_0_1"
                       
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpResponse response = null;
            HttpPost httpPost = new HttpPost(reqUri + "?" + parm);
            Header ContentTypeHeader = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader(ContentTypeHeader);
            try {
                response = httpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            int statusCode = response.getStatusLine().getStatusCode();
            String getResult = null;
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("error status code: " + statusCode);
            } else {
                try {
                    getResult = EntityUtils.toString(response.getEntity());
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (getResult != null) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
                    System.out.println("retcode: " + jsonObject.getString("retcode"));
                } catch (JSONException jsonException) {
                    jsonException.printStackTrace();
                }
            }
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

posted @ 2016-08-17 09:37  拽拽绅士  阅读(675)  评论(0编辑  收藏  举报

Java | Golang | Python | php