Java源码示例:jodd.http.HttpRequest
示例1
@Override
public Boolean execute(String uri, String materialId) throws WxErrorException, IOException {
HttpRequest request = HttpRequest.post(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
request.query("media_id", materialId);
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String responseContent = response.bodyText();
WxError error = WxError.fromJson(responseContent, WxType.MP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return true;
}
}
示例2
@Override
public WxMpMaterialNews execute(String uri, String materialId) throws WxErrorException, IOException {
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
HttpRequest request = HttpRequest.post(uri)
.withConnectionProvider(requestHttp.getRequestHttpClient())
.body(WxGsonBuilder.create().toJson(ImmutableMap.of("media_id", materialId)));
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String responseContent = response.bodyText();
this.logger.debug("响应原始数据:{}", responseContent);
WxError error = WxError.fromJson(responseContent, WxType.MP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class);
}
}
示例3
@Override
public WxMpMaterialVideoInfoResult execute(String uri, String materialId) throws WxErrorException, IOException {
HttpRequest request = HttpRequest.post(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
request.query("media_id", materialId);
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String responseContent = response.bodyText();
WxError error = WxError.fromJson(responseContent, WxType.MP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
} else {
return WxMpMaterialVideoInfoResult.fromJson(responseContent);
}
}
示例4
@Override
public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException {
if (data == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build());
}
HttpRequest request = HttpRequest.post(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
request.form("media", data);
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String responseContent = response.bodyText();
WxError error = WxError.fromJson(responseContent, WxType.MP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return WxMediaImgUploadResult.fromJson(responseContent);
}
示例5
@Override
public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException {
HttpRequest request = HttpRequest.post(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
request.form("media", file);
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String responseContent = response.bodyText();
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return WxMediaUploadResult.fromJson(responseContent);
}
示例6
@Override
public byte[] postForBytes(String url, String requestStr, boolean useKey) throws WxPayException {
try {
HttpRequest request = this.buildHttpRequest(url, requestStr, useKey);
byte[] responseBytes = request.send().bodyBytes();
final String responseString = Base64.encodeToString(responseBytes);
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据(Base64编码后)】:{}", url, requestStr, responseString);
wxApiData.set(new WxPayApiData(url, requestStr, responseString, null));
return responseBytes;
} catch (Exception e) {
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
throw new WxPayException(e.getMessage(), e);
}
}
示例7
@Override
public String post(String url, String requestStr, boolean useKey) throws WxPayException {
try {
HttpRequest request = this.buildHttpRequest(url, requestStr, useKey);
String responseString = this.getResponseString(request.send());
this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据】:{}", url, requestStr, responseString);
wxApiData.set(new WxPayApiData(url, requestStr, responseString, null));
return responseString;
} catch (Exception e) {
this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
throw new WxPayException(e.getMessage(), e);
}
}
示例8
@Override
public File execute(String uri, WxMpQrCodeTicket ticket) throws WxErrorException, IOException {
if (ticket != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
}
uri += uri.endsWith("?")
? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8")
: "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8");
}
HttpRequest request = HttpRequest.get(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String contentTypeHeader = response.header("Content-Type");
if (MimeTypes.MIME_TEXT_PLAIN.equals(contentTypeHeader)) {
String responseContent = response.bodyText();
throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
}
try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) {
return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
}
}
示例9
@Override
public InputStream execute(String uri, String materialId) throws WxErrorException, IOException {
HttpRequest request = HttpRequest.post(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
request.query("media_id", materialId);
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) {
// 下载媒体文件出错
byte[] responseContent = IOUtils.toByteArray(inputStream);
String responseContentString = new String(responseContent, StandardCharsets.UTF_8);
if (responseContentString.length() < 100) {
try {
WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class);
if (wxError.getErrorCode() != 0) {
throw new WxErrorException(wxError);
}
} catch (com.google.gson.JsonSyntaxException ex) {
return new ByteArrayInputStream(responseContent);
}
}
return new ByteArrayInputStream(responseContent);
}
}
示例10
@Override
public String execute(String uri, String postEntity) throws WxErrorException, IOException {
HttpConnectionProvider provider = requestHttp.getRequestHttpClient();
ProxyInfo proxyInfo = requestHttp.getRequestHttpProxy();
HttpRequest request = HttpRequest.post(uri);
if (proxyInfo != null) {
provider.useProxy(proxyInfo);
}
request.withConnectionProvider(provider);
if (postEntity != null) {
request.bodyText(postEntity);
}
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String responseContent = response.bodyText();
if (responseContent.isEmpty()) {
throw new WxErrorException(WxError.builder().errorCode(9999).errorMsg("无响应内容")
.build());
}
if (responseContent.startsWith("<xml>")) {
//xml格式输出直接返回
return responseContent;
}
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return responseContent;
}
示例11
@Override
public File execute(String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
}
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
}
HttpRequest request = HttpRequest.get(uri);
if (requestHttp.getRequestHttpProxy() != null) {
requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
}
request.withConnectionProvider(requestHttp.getRequestHttpClient());
HttpResponse response = request.send();
response.charset(StringPool.UTF_8);
String contentType = response.header("Content-Type");
if (contentType != null && contentType.startsWith("application/json")) {
// application/json; encoding=utf-8 下载媒体文件出错
throw new WxErrorException(WxError.fromJson(response.bodyText()));
}
String fileName = new HttpResponseProxy(response).getFileName();
if (StringUtils.isBlank(fileName)) {
return null;
}
try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) {
return FileUtils.createTmpFile(inputStream,
FilenameUtils.getBaseName(fileName),
FilenameUtils.getExtension(fileName),
super.tmpDirFile);
}
}
示例12
/**
* get请求
* @param url url地址
* @param host 主机地址/根域名
* @param param 参数
* @return
*/
public Result doGet(String host,String url,Map<String,String>param)
{
//Map<String,Object> result=new HashMap<>();
Result result=new Result();
long responseTime=0;
long startTime=0;
long endTime=0;
startTime=System.currentTimeMillis();
HttpResponse httpResponse= HttpRequest.get(host+url).query(param).send();
String statusCode="";
String responseText="";
String responseHeader="";
String requestHeader="";
endTime=System.currentTimeMillis();
//获取响应时间
responseTime=endTime-startTime;
//获取响应字符串
responseText=httpResponse.bodyText();
//获取返回请求状态码
statusCode=Long.toString(httpResponse.statusCode());
//获取响应头
responseHeader=httpResponse.headers().toString();
//获取请求头
requestHeader=httpResponse.getHttpRequest().headers().toString();
result.setResult("statusCode",statusCode);
result.setResult("responseText",responseText);
//请求开始时间
result.setResult("startTime",startTime);
//请求结束时间
result.setResult("endTime",endTime);
result.setResult("responseTime",responseTime);
//获取header头
result.setResult("headerText",responseHeader);
return result;
}
示例13
/**
* Sends mail by SendClound.
*
* @param toMails to mails
* @param templateName template name
* @param subject subject
* @param variables template variables
*/
public static void send(final String subject, final String templateName,
final List<String> toMails, final Map<String, List<String>> variables) {
if (null == toMails || toMails.isEmpty()) {
return;
}
try {
final Map<String, Object> formData = new HashMap<String, Object>();
formData.put("api_user", API_USER);
formData.put("api_key", API_KEY);
formData.put("from", "[email protected]" + Latkes.getServerHost());
formData.put("fromname", "Sym");
formData.put("subject", subject);
formData.put("template_invoke_name", templateName);
final JSONObject args = new JSONObject();
args.put("to", new JSONArray(toMails));
final JSONObject sub = new JSONObject();
args.put("sub", sub);
for (final Map.Entry<String, List<String>> var : variables.entrySet()) {
final JSONArray value = new JSONArray(var.getValue());
sub.put(var.getKey(), value);
}
formData.put("substitution_vars", args.toString());
formData.put("resp_email_id", "true");
final HttpResponse response = HttpRequest.post("http://sendcloud.sohu.com/webapi/mail.send_template.json")
.form(formData).send();
LOGGER.log(Level.INFO, response.bodyText());
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Send mail error", e);
}
}
示例14
public Result doPost(String host,String url,String bodyJsonParams,Map<String, String> headerParams){
Result result=new Result();
long responseTime=0;//响应时间
long startTime=0;//开始请求时间
long endTime=0;//结束请求时间
String statusCode="";
String responseText="";
String requestHeader="";
HttpRequest httpRequest= new HttpRequest().post(host+url);
if (!headerParams.isEmpty())
{
for (Map.Entry<String,String> entry:headerParams.entrySet())
{
httpRequest.header(entry.getKey(),entry.getValue());
}
}
//body参数
if (!bodyJsonParams.isEmpty())
{
httpRequest.body(bodyJsonParams);
}
try {
//开始发送post请求时间
startTime=System.currentTimeMillis();
HttpResponse httpResponse=httpRequest.send();
//结束post请求时间
endTime=System.currentTimeMillis();
//响应时间
responseTime=endTime-startTime;
requestHeader=httpResponse.getHttpRequest().headers().toString();
statusCode=Long.toString(httpResponse.statusCode());
responseText=httpResponse.bodyText();
//获取返回请求状态码
result.setResult("statusCode",statusCode);
//获取body响应字符串
result.setResult("responseText",responseText);
//请求开始时间
result.setResult("startTime",startTime);
//请求结束时间
result.setResult("endTime",endTime);
//获取响应时间
result.setResult("responseTime",responseTime);
//获取header头
result.setResult("headerText",httpResponse.headers().toString());
}catch (Exception e) {
System.out.println("发送post请求失败!");
e.printStackTrace();
}
return result;
}
示例15
/**
* 不带安全认证参数post请求
* @param url url地址
* @param bodyParams body参数
* @param headerParams 头参数
* @return 返回包含响应时间,响应状态码,响应字符串数据信息的Map
*/
public Result dopost(String host,String url, Map<String,Object> bodyParams, Map<String, String> headerParams)
{
//Map<String,Object> result=new HashMap<>();
String requestHeader="";
Result result=new Result();
long responseTime=0;//响应时间
long startTime=0;//开始请求时间
long endTime=0;//结束请求时间
String statusCode="";
String responseText="";
HttpRequest httpRequest= new HttpRequest().post(host+url);
//header头参数
if (!headerParams.isEmpty())
{
for (Map.Entry<String,String> entry:headerParams.entrySet())
{
httpRequest.header(entry.getKey(),entry.getValue());
}
}
//body参数
if (!bodyParams.isEmpty())
{
httpRequest.form(bodyParams);
}
try {
startTime=System.currentTimeMillis();
HttpResponse httpResponse=httpRequest.send();
endTime=System.currentTimeMillis();
responseTime=endTime-startTime;
responseText=httpResponse.bodyText();
statusCode=Long.toString(httpResponse.statusCode());
//获取请求头
requestHeader=httpResponse.getHttpRequest().headers().toString();
//获取返回请求状态码
result.setResult("statusCode",statusCode);
//获取响应字符串
result.setResult("responseText",responseText);
//请求开始时间
result.setResult("startTime",startTime);
//请求结束时间
result.setResult("endTime",endTime);
//获取响应时间
result.setResult("responseTime",responseTime);
//获取响应header头
result.setResult("headerText",httpResponse.headers().toString());
}catch (Exception e) {
System.out.println("发送post请求失败!");
e.printStackTrace();
}
return result;
}
示例16
/**
* 不带安全认证/头参数post请求(只需填写body参数)
* @param url url地址
* @param host 主机地址/根域名
* @param bodyParams body请求参数
* @return 返回包含响应时间,响应状态码,响应字符串数据信息的Map
*/
public Result dopost(String host,String url, Map<String,Object> bodyParams)
{
//Map<String,Object> result=new HashMap<>();
String requestHeader="";
Result result=new Result();
long responseTime=0;//响应时间
long startTime=0;//开始请求时间
long endTime=0;//结束请求时间
HttpRequest httpRequest= new HttpRequest().post(host+url);
String statusCode="";
String responseText="";
//body参数
if (!bodyParams.isEmpty())
{
httpRequest.form(bodyParams);
}
try {
startTime=System.currentTimeMillis();
HttpResponse httpResponse=httpRequest.send();
endTime=System.currentTimeMillis();
responseTime=endTime-startTime;
responseText=httpResponse.bodyText();
statusCode=Long.toString(httpResponse.statusCode());
//获取请求头
requestHeader=httpResponse.getHttpRequest().headers().toString();
//获取返回请求状态码
result.setResult("statusCode",httpResponse.statusCode());
//获取响应字符串
result.setResult("responseText",httpResponse.bodyText());
//请求开始时间
result.setResult("startTime",startTime);
//请求结束时间
result.setResult("endTime",endTime);
//获取响应时间
result.setResult("responseTime",responseTime);
}catch (Exception e) {
System.out.println("发送post请求失败!");
e.printStackTrace();
}
return result;
}
示例17
/**
* 不带任何参数的post请求
* @param url url地址+
* @param host 主机地址/根域名
* @return 返回包含响应时间,响应状态码,响应字符串数据信息的Map
*/
public Result dopost(String host,String url)
{
//Map<String,Object> result=new HashMap<>();
String bodyParams="";
Result result=new Result();
long responseTime=0;//响应时间
long startTime=0;//开始请求时间
long endTime=0;//结束请求时间
HttpRequest httpRequest= new HttpRequest().post(host+url);
String statusCode="";
String responseText="";
String responseHeader="";
String requestHeader="";
try {
startTime=System.currentTimeMillis();
HttpResponse httpResponse=httpRequest.send();
endTime=System.currentTimeMillis();
//请求开始时间
result.setResult("startTime",startTime);
//请求结束时间
result.setResult("endTime",endTime);
//获取响应时间
responseTime=endTime-startTime;
//获取响应字符串
responseText=httpResponse.bodyText();
//获取返回请求状态码
statusCode=Long.toString(httpResponse.statusCode());
//获取响应header头
responseHeader=httpResponse.headers().toString();
//获取请求头
requestHeader=httpResponse.getHttpRequest().headers().toString();
result.setResult("statusCode",statusCode);
result.setResult("responseText",responseText);
result.setResult("responseTime",responseTime);
result.setResult("headerText",responseHeader);
bodyParams=httpRequest.bodyText();
}catch (Exception e) {
System.out.println("发送post请求失败!");
e.printStackTrace();
}
return result;
}