API Request Get和Post
在Http传输协议中Get和Post是最常用的两种, HTTP 的工作方式是客户机与服务器之间的请求-应答协议。web 浏览器可能是客户端,而计算机上的网络应用程序也可能作为服务器端。举例:客户端(浏览器)向服务器提交 HTTP 请求;服务器向客户端返回响应。响应包含关于请求的状态信息以及可能被请求的内容。
-
GET - 从指定的资源请求数据。
-
GET 方法查询字符串(名称/值对)是在 GET 请求的 URL 中发送的:url和请求体之间用”?”分割,不同参数之间用”&”分隔,%XX中的XX为该符号以16进制表示的ASCII,如果数据是英文字母/数字,原样发送,如果是空格,转换为+,如果是中文/其他字符,则直接把字符串用BASE64加密。
/test/demo_form.asp?name1=value1&name2=value2
POST - 向指定的资源提交要被处理的数据
-
Post查询字符串(名称/值对)是在 POST 请求的 HTTP 消息主体中发送的,POST把提交的数据则放置在是HTTP包的包体中,Post没有限制提交的数据。
POST /test/demo_form.asp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
用java封装的例子
package com.framework.automation.cucumber.utilities;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
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.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
//连接池
private static PoolingHttpClientConnectionManager connectionMgr;
//超时时间
private static final int MAX_TIMEOUT = 7000;
private static RequestConfig requestConfig;
static{
//设置连接池
connectionMgr = new PoolingHttpClientConnectionManager();
//设置连接池大小
connectionMgr.setMaxTotal(100);
connectionMgr.setDefaultMaxPerRoute(connectionMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
//设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
//设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
//设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
requestConfig = configBuilder.build();
}
/**
* GET 请求 带输入参数
* @param Url 请求host地址
* @param params 参数
* @return
*/
public static String httpGet(String Url,Map<String, Object>params)
{
//返回结果
String result = null;
//拼接url
StringBuilder builder = new StringBuilder(Url);
if (Url.contains("?")) {
builder.append("&");
}else{
builder.append("?");
}
int i=0;
for (String key : params.keySet()) {
if (i != 0 ) {
builder.append("&");
}
builder.append(key);
builder.append("=");
builder.append(params.get(key));
i++;
}
String apiUrl = builder.toString();
System.out.println(apiUrl);
//创建client
HttpClient client = HttpClients.createDefault();
try {
HttpGet get = new HttpGet(apiUrl);
HttpResponse response = client.execute(get);
//获取请求状态码
int statusCode = response.getStatusLine().getStatusCode();
//System.out.println(statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity,"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* POST 请求
* @param url 请求url
* @param params post提交参数
* @return
*/
public static String httpPost(String url,Map<String, Object>params)
{
HttpClient client = HttpClients.createDefault();
String result = null;
try {
HttpPost post = new HttpPost(url);
//添加post提交参数
ArrayList<NameValuePair> pairList = new ArrayList<NameValuePair>();
for(Map.Entry<String, Object> entry:params.entrySet())
{
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
post.setEntity(new UrlEncodedFormEntity(pairList,"UTF-8"));
System.out.println(pairList);
HttpResponse response = client.execute(post);
//获取状态码
int statueCode = response.getStatusLine().getStatusCode();
//System.out.println(statueCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
运行结果
package com.framework.automation.cucumber.run;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
//import org.skyscreamer.jsonassert.JSONAssert;
import com.framework.automation.cucumber.utilities.HttpUtil;
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
import com.framework.automation.cucumber.utilities.TestDataCsvReader;
public class Running {
private final static String JSON_DATA = "{" + " \"geodata\": [" + " {" + " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\"," + " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\"," + " \"longitude\" : \"-121.88670166666667\"" + " },"
+ " {" + " \"id\": \"2\"," + " \"name\": \"Johnny Depp\"," + " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\"," + " \"longitude\" : \"-121.884985\"" + " }" + " ]" + "}";
private static final String jsonFilePath = System.getProperty("user.dir")
+ "/src/main/resources/testdata/example/jsonTestFile.json";
public static void main(final String[] argv) throws Exception {
// final JSONObject obj = new JSONObject(JSON_DATA);
// final JSONArray geodata = obj.getJSONArray("geodata");
// final int n = geodata.length();
// for (int i = 0; i < n; ++i) {
// final JSONObject person = geodata.getJSONObject(i);
// System.out.println(person.getInt("id"));
// System.out.println(person.getString("name"));
// System.out.println(person.getString("gender"));
// System.out.println(person.getDouble("latitude"));
// System.out.println(person.getDouble("longitude"));
// }
// TestDataCsvReader.log.info(TestDataCsvReader.loadBusinessObjectFromCsv("testdata/example/hopperTest.csv",
// "hopper", ""));
//
// FileReader reader = new FileReader(jsonFilePath);
// JSONParser jsonParser = new JSONParser();
// JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
//
// // get a String from the JSON object
// long id = (long) jsonObject.get("id");
// String firstName = (String) jsonObject.get("firstname");
// JSONArray lang = (JSONArray) jsonObject.get("languages");
//
// System.out.println("The id is: " + id);
// System.out.println("The first name is: " + firstName);
// for (int i = 0; i < lang.size(); i++) {
// System.out.println("The " + i + " element is: " + lang.get(i));
// }
//
// Iterator i = lang.iterator();
//
// // take each value from the json array separately
// while (i.hasNext()) {
// JSONObject innerObj = (JSONObject) i.next();
// System.out.println("language " + innerObj.get("lang") +
// " with level " + innerObj.get("knowledge"));
// }
//
// // handle a structure into the json object
// JSONObject structure = (JSONObject) jsonObject.get("job");
// System.out.println("Into job structure, name: " + structure.get("name"));
// String expected = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}";
// String actual = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}";
// //JSONAssert.assertEquals(expected, actual, false);
//
// String test1= "{name:\"Joe\", id:1}";
// String test2= "{id:1,name:\"Joe\"}";
// JsonParser parser = new JsonParser();
// JsonElement o1 = parser.parse(test1);
// JsonElement o2 = parser.parse(test2);
// System.out.println(o1.equals(o2));
String urlStr = "https://openapi.youdao.com/api";
HttpUtil util = new HttpUtil();
Map<String, Object> params = new HashMap<String, Object>();
params.put("q", "good");
params.put("salt", "1496238482428");
params.put("sign", "02E15CDAF871B698FE04EE32FD2CF155");
params.put("from", "en");
params.put("appKey", "7743eee7f7e11d75");
params.put("to", "zh-CHS");
String resultPost = util.httpPost(urlStr, params);
String resultGet = util.httpGet(urlStr, params);
System.out.println(resultPost);
System.out.println(resultGet);
JsonParser parser = new JsonParser();
JsonElement o1 = parser.parse(resultPost);
JsonElement o2 = parser.parse(resultGet);
System.out.println(o1.equals(o2));
}
}
[q=good, salt=1496238482428, sign=02E15CDAF871B698FE04EE32FD2CF155, from=en, appKey=7743eee7f7e11d75, to=zh-CHS]
https://openapi.youdao.com/api?q=good&salt=1496238482428&sign=02E15CDAF871B698FE04EE32FD2CF155&from=en&appKey=7743eee7f7e11d75&to=zh-CHS
{“web”:[{“value”:[“好”,”善”,”商品”],”key”:”Good”},{“value”:[“公共物品”,”公益事业”,”公共财”],”key”:”public good”},{“value”:[“干的出色”,”干得好”,”好工作”],”key”:”Good Job”}],”query”:”good”,”translation”:[“很好”],”errorCode”:”0”,”dict”:{“url”:”yddict://m.youdao.com/dict?le=eng&q=good”},”webdict”:{“url”:”http://m.youdao.com/dict?le=eng&q=good“},”basic”:{“us-phonetic”:”ɡ?d”,”phonetic”:”g?d”,”uk-phonetic”:”g?d”,”explains”:[“n. 好处;善行;慷慨的行为”,”adj. 好的;优良的;愉快的;虔诚的”,”adv. 好”,”n. (Good)人名;(英)古德;(瑞典)戈德”]},”l”:”en2zh-CHS”}
{“web”:[{“value”:[“好”,”善”,”商品”],”key”:”Good”},{“value”:[“公共物品”,”公益事业”,”公共财”],”key”:”public good”},{“value”:[“干的出色”,”干得好”,”好工作”],”key”:”Good Job”}],”query”:”good”,”translation”:[“很好”],”errorCode”:”0”,”dict”:{“url”:”yddict://m.youdao.com/dict?le=eng&q=good”},”webdict”:{“url”:”http://m.youdao.com/dict?le=eng&q=good“},”basic”:{“us-phonetic”:”ɡ?d”,”phonetic”:”g?d”,”uk-phonetic”:”g?d”,”explains”:[“n. 好处;善行;慷慨的行为”,”adj. 好的;优良的;愉快的;虔诚的”,”adv. 好”,”n. (Good)人名;(英)古德;(瑞典)戈德”]},”l”:”en2zh-CHS”}
true