httpclient的get和post

pom.xml

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.5</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>

 

class代码
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.Test;

import java.io.*;

/**
 * Created by win7 on 2016/7/28.
 */
public class HttpClient {
    @Test
    public void test_get() {
        String url = "http://ssov1.59iedu.com/login?TARGET=http://med.ihbedu.com:80/gateway/web/sso/auth&js&callback=loginThen&1470491151264&nocache=1470491171451";
        this.httpGet(url);
    }

    @Test
    public void test_post() {
        String postUrl = "http://test.ihbedu.com:1457/gateway/web/home/registered/createUserAccount?_q_=1458452488928";
        try {
            String userNameOrPhone = "15988880018";
            JSONObject parsers = new JSONObject();
            parsers.put("phone", userNameOrPhone);
            parsers.put("password", "000000");
            parsers.put("picValidateCode", "c4kx");
            parsers.put("remoteValidateCode", "success");
            parsers.put("phoneValidateCode", "003023");
            parsers.put("yesIDo", true);
            JSONArray provinceArray = new JSONArray();
            JSONObject provinceInfoObject = new JSONObject();
            provinceInfoObject.put("id", "110000");
            provinceInfoObject.put("municipalities", true);
            provinceInfoObject.put("name", "北京市");
            provinceInfoObject.put("regionPath", "/110000");
            provinceArray.put(provinceInfoObject);
            parsers.put("province", provinceArray);
            parsers.put("schoolId", "122");
            JSONArray schoolArray = new JSONArray();
            JSONObject schoolInfoObject = new JSONObject();
            schoolInfoObject.put("areaPath", "/110000");
            schoolInfoObject.put("available", true);
            schoolInfoObject.put("id", "122");
            schoolInfoObject.put("name", "北京(其他)");
            schoolInfoObject.put("platformId", "2c9180e5520a5e70015214fb2849000a");
            schoolInfoObject.put("platformVersionId", "2c9180e5520a6063015214fc062d0006");
            schoolInfoObject.put("projectId", "-1");
            schoolInfoObject.put("subProjectId", "-1");
            schoolArray.put(schoolInfoObject);
            parsers.put("school", schoolArray);
            parsers.put("name", userNameOrPhone);
            parsers.put("sex", "1");
            parsers.put("registerSource", 1);
            parsers.put("registerType", 11);
            parsers.put("accountType", 1);
            this.httpPost(postUrl, parsers);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String httpGet(String url) {
        String responseStr = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();//建立httpclient
        HttpGet httpGet = new HttpGet(url);//建立httpget
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);//执行get请求,并结果保存
            HttpEntity httpEntity = response.getEntity();//将保存的response转为实体
            try {

                if (response.getStatusLine().getStatusCode() == 200) {
                    responseStr = EntityUtils.toString(httpEntity);
                } else
                    responseStr = "error";

            } finally {
                this.writeTxt("src\\main\\resources\\log\\response.txt", responseStr);//把response写入txt中
                EntityUtils.consume(httpEntity);//关闭实体
                response.close();//关闭response
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();//关闭httpclient
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseStr;
    }

    public void httpPost(String url, JSONObject parser) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (parser != null) {
            StringEntity stringEntity = new StringEntity(parser.toString(), "utf-8");//构造字符串数据
            stringEntity.setContentEncoding("utf-8");//设置内容编码格式
            stringEntity.setContentType("application/json");//设置内容类型
            httpPost.setEntity(stringEntity);//设置请求数据
        }
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            this.writeTxt("src\\main\\resources\\log\\response.txt", EntityUtils.toString(response.getEntity()));//把response写入txt中
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();//关闭httpclient
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 信息写入txt中
     *
     * @param path    路径
     * @param content 写入的内容
     */
    public void writeTxt(String path, String content) {
        try {
            FileWriter fileWriter = new FileWriter(path, true);
            fileWriter.write(content);
            fileWriter.flush();//关闭流
            fileWriter.close();//关闭资源
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2016-08-03 09:55  xxyBlogs  阅读(196)  评论(0编辑  收藏  举报