发起get请求,参数带在url后面
private String getResult(String url) throws MicroRunTimeException {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
BasicResponseHandler responseHandler = new BasicResponseHandler();
return httpClient.execute(httpGet, responseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
发起post请求,content_type
为application/json
时:
private String postResult(String url, Map<String, String> paramMap) throws MicroRunTimeException {
try {
String jsonData = JSON.toJSONString(paramMap);
Response response = Request.Post(url)
.addHeader(CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8)
.bodyByteArray(jsonData.getBytes()) //注意,此处是传递json格式参数
.socketTimeout(OUT_TIME)
.connectTimeout(CONNECT_TIMEOUT)
.execute();
String content = response.returnContent().asString();
return content;
}catch (Exception e) {
e.printStackTrace();
}
}
发起post请求,content_type
为application/x-www-form-urlencoded
时:
public String postResultFForm(String url, Map<String, String> paramMap) throws MicroRunTimeException {
Form form = Form.form();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
form.add(entry.getKey(), entry.getValue());
}
try {
Content content = Request.Post(url)
.addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED_UTF_8)
.bodyForm(form.build(), allCharset).socketTimeout(OUT_TIME).connectTimeout(CONNECT_TIMEOUT).execute().returnContent();
return content.asString();
} catch (Exception e) {
e.printStackTrace();
}
}