Java Code Examples for org.apache.http.Consts#UTF_8

The following examples show how to use org.apache.http.Consts#UTF_8 . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public boolean isLogin(UserModel userModel) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userModel.getUsername());
    HttpPost httpPost = new HttpPost(apiConfig.getUamtkStatic());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("appid", "otn"));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    String response = httpUtil.post(httpPost);
    Gson jsonResult = new Gson();
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if ("0.0".equals(rsmap.get("result_code").toString())) {
        userModel.setUamtk(rsmap.get("newapptk").toString());
        UserTicketStore.httpUtilStore.put(userModel.getUsername(), httpUtil);
        return true;
    } else {
        return false;
    }
}
 
Example 2
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public String uamauthclient(String userName, String tk) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userName);
    HttpPost httpPost = new HttpPost(apiConfig.getUamauthclient());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("tk", tk));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    Gson jsonResult = new Gson();
    String response = httpUtil.post(httpPost);
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if ("0.0".equals(rsmap.getOrDefault("result_code", "").toString())) {
        UserTicketStore.httpUtilStore.put(userName, httpUtil);
        return rsmap.get("apptk").toString();
    }
    return null;
}
 
Example 3
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public boolean checkUser(String userName) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userName);
    HttpPost httpPost = new HttpPost(apiConfig.getCheckUser());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("_json_att", ""));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    Gson jsonResult = new Gson();
    String response = httpUtil.post(httpPost);
    if (StringUtils.isEmpty(response)) {
        log.error("用户校验失败,不能下单!");
        return false;
    }
    Map rsmap = jsonResult.fromJson(response, Map.class);
    rsmap = jsonResult.fromJson(rsmap.getOrDefault("data", "").toString(), Map.class);
    if (rsmap.getOrDefault("flag", "").toString().equals("true")) {
        log.info("用户校验成功,准备下单购票");
        return true;
    }
    log.error("用户校验失败,不能下单!");
    return false;
}
 
Example 4
Source File: RestDataBindingTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testForm() throws IOException {
    Assert.assertEquals("form", restService.bindForm("form"));

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8803/rest/bindForm");

    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("formP", "formBBB"));
    HttpEntity httpEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);

    httpPost.setEntity(httpEntity);

    HttpResponse httpResponse = httpclient.execute(httpPost);
    String result = EntityUtils.toString(httpResponse.getEntity());

    Assert.assertEquals("formBBB", result);
}
 
Example 5
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public List<PassengerModel> getPassengerDTOs(String userName, String token) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userName);
    List<PassengerModel> passengerModelList = new ArrayList<>();
    HttpPost httpPost = new HttpPost(apiConfig.getGetPassengerDTOs());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("_json_att", ""));
    formparams.add(new BasicNameValuePair("REPEAT_SUBMIT_TOKEN", token));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    Gson jsonResult = new Gson();
    String response = httpUtil.post(httpPost);
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if (rsmap.getOrDefault("status", "").toString().equals("true")) {
        rsmap = (Map<String, Object>) rsmap.get("data");
        List<Map<String, String>> passengers = (List<Map<String, String>>) rsmap
                .get("normal_passengers");
        if (!CollectionUtils.isEmpty(passengers)) {
            passengers.forEach(passenger -> {
                PassengerModel passengerModel = new PassengerModel(passenger);
                passengerModelList.add(passengerModel);
            });
        }
    }
    return passengerModelList;
}
 
Example 6
Source File: QANARY.java    From chatbot with Apache License 2.0 6 votes vote down vote up
private String makeRequest(String question) {
        try {
            HttpPost httpPost = new HttpPost(URL);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("query", question));
//            params.add(new BasicNameValuePair("lang", "it"));
            params.add(new BasicNameValuePair("kb", "dbpedia"));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);

            // Error Scenario
            if(response.getStatusLine().getStatusCode() >= 400) {
                logger.error("QANARY Server could not answer due to: " + response.getStatusLine());
                return null;
            }

            return EntityUtils.toString(response.getEntity());
        }
        catch(Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
 
Example 7
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public boolean checkRandCodeAnsyn(String position, String token) {
    HttpUtil httpUtil = new HttpUtil();
    HttpPost httpPost = new HttpPost(apiConfig.getCheckRandCodeAnsyn());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("randCode", position));
    formparams.add(new BasicNameValuePair("REPEAT_SUBMIT_TOKEN", token));
    formparams.add(new BasicNameValuePair("rand", "randp"));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    String response = httpUtil.post(httpPost);

    Gson jsonResult = new Gson();
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if (rsmap.getOrDefault("status", "").toString().equals("true")) {
        return true;
    }
    log.error("验证码错误", rsmap.get("result_message"));
    return false;
}
 
Example 8
Source File: HttpGetPostRequestMokUtil.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
public static HttpResponse httpClientForPost(String url,List<NameValuePair> list,HttpClient httpClient) throws Exception {
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
post.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(post);
return httpResponse;
  }
 
Example 9
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void createFolderSimpleForm(CloseableHttpClient httpclient) throws Exception { 
	
	// This will create a tree starting from the Root folder (not in the Default workspace)
	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("folderPath", "/LogicalDOC/USA/NJ/Fair Lawn/createSimple"));
	
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
	
	HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/folder/createSimpleForm");
	httppost.setEntity(entity);		

	CloseableHttpResponse response = httpclient.execute(httppost);
	int code = response.getStatusLine().getStatusCode();
	System.out.println("HTTPstatus code: "+ code);
	if (code == HttpStatus.SC_OK) {
	} else {
		//log.warn("status code is invalid: {}", code);
		System.err.println("status code is invalid: "+ code);
		throw new Exception(response.getStatusLine().getReasonPhrase());
	}				
	
	try {
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody);
		}
	} finally {
		response.close();
	}
}
 
Example 10
Source File: CommentsRestClient.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String doPostLogin(String username, String password) throws Exception {
	
	CloseableHttpClient httpclient = getHTTPClient(username, password);

	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("username", username));
	formparams.add(new BasicNameValuePair("password", password));
	
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
	
	HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/auth/login");
	httppost.setEntity(entity);	

	CloseableHttpResponse response = httpclient.execute(httppost);
	try {
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody);
			return respoBody;
		}
	} finally {
		response.close();
	}

	return null;
}
 
Example 11
Source File: CommonUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Do http post.
 *
 * @param url the url
 * @param requestBody the request body
 * @return String
 * @throws Exception the exception
 */
public static String doHttpPost(final String url, final Map<String,String> requestBody) throws Exception {
	try {
		
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		
		List<NameValuePair> form = new ArrayList<>();
		requestBody.forEach((k,v)-> {
			form.add(new BasicNameValuePair(k,v));
		});
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);
		httppost.setEntity(entity);
		
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if(statusCode==HttpStatus.SC_OK || statusCode==HttpStatus.SC_CREATED)
		{
			return EntityUtils.toString(httpresponse.getEntity());
		}else{
			logger.error(httpresponse.getStatusLine().getStatusCode() + "---" + httpresponse.getStatusLine().getReasonPhrase());
			throw new Exception("unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		logger.error("ParseException in getHttpPost :"+parseException.getMessage());
		throw parseException;
	} catch (Exception exception) {
		logger.error("Exception in getHttpPost :"+exception.getMessage());
		throw exception;
	 }
}
 
Example 12
Source File: URIUtil.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert byte array to a UTF-8 string value.
 * @param bytes byte array
 * @return ASCII string
 */
public static String getString(final byte[] bytes) {
    if (bytes == null) {
        throw new IllegalArgumentException("Parameter may not be null");
    }

    return new String(bytes, Consts.UTF_8);
}
 
Example 13
Source File: ApacheSimplePostRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String execute(String uri, String postEntity) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    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;
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 14
Source File: WeChatNotice.java    From ticket with GNU General Public License v3.0 5 votes vote down vote up
private HttpPost buildHttpRequest(String serverSckey,String message,String topic){
    String url = apiConfig.getServerWechat() + serverSckey + ".send";
    HttpPost httpPost = new HttpPost(url);
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("text", topic));
    formparams.add(new BasicNameValuePair("desp", message));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    return httpPost;
}
 
Example 15
Source File: LocalRestChannel.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void doSendResponse(RestResponse response) {
    status = response.status().getStatus();

    byte[] bytes = response.content().toBytes();
    long length = bytes.length;
    Args.check(length <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
    if(length < 0) {
        length = 4096;
    }

    InputStream instream =  new ByteArrayInputStream(bytes);
    InputStreamReader reader = new InputStreamReader(instream, Consts.UTF_8);
    CharArrayBuffer buffer = new CharArrayBuffer((int)length);
    char[] tmp = new char[1024];

    int l;
    try {
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        content = buffer.toString();
    } catch (IOException e) {
        status = RestStatus.INTERNAL_SERVER_ERROR.getStatus();
        content = "IOException: " + e.getMessage();
    } finally {
        try {
            reader.close();
            instream.close();
        } catch (IOException e1) {
            content = "IOException: " + e1.getMessage();
        } finally {
            count.countDown();
        }
    }
}
 
Example 16
Source File: O365Token.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void refreshToken() throws IOException {
    ArrayList<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("grant_type", "refresh_token"));
    parameters.add(new BasicNameValuePair("refresh_token", refreshToken));
    parameters.add(new BasicNameValuePair("redirect_uri", redirectUri));
    parameters.add(new BasicNameValuePair("client_id", clientId));
    parameters.add(new BasicNameValuePair("resource", "https://outlook.office365.com/"));

    RestRequest tokenRequest = new RestRequest(tokenUrl, new UrlEncodedFormEntity(parameters, Consts.UTF_8));

    executeRequest(tokenRequest);
}
 
Example 17
Source File: HttpGetPostRequestMokUtil.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
public static HttpResponse httpClientForPost(String url,String ip,List<NameValuePair> list,CloseableHttpClient closeableHttpClient) throws Exception {
HttpPost post = new HttpPost(url);
post.addHeader("x-forwarded-for", ip);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
post.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = closeableHttpClient.execute(post);
return httpResponse;
  }
 
Example 18
Source File: CommentsRestClient.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void addCommentForm(String sid, Long docID) throws Exception {

		//String output = null;

			String url = BASE_PATH + "/services/mobile/comments/addcommentform/$SID/$ID";
			url = url.replace("$SID", sid);
			url = url.replace("$ID", docID.toString());
			
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("content", "This is a comment added via CommentForm"));
			
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
			
			HttpPost httppost = new HttpPost(url);
			httppost.addHeader(new BasicHeader("Accept", "application/json"));
			//httppost.addHeader(new BasicHeader("Accept", "application/xml"));
			httppost.setEntity(entity);	
			
			CloseableHttpClient httpclient = getHTTPClient("admin", "admin123");
			CloseableHttpResponse response = httpclient.execute(httppost);
			
			try {
				int code = response.getStatusLine().getStatusCode();
				System.out.println("HTTPstatus code: "+ code);
				if (code == HttpStatus.SC_OK) {
					HttpEntity rent = response.getEntity();
					if (rent != null) {
						String respoBody = EntityUtils.toString(rent, "UTF-8");
						System.out.println(respoBody);
					}
				} else {
					//log.warn("status code is invalid: {}", code);
					System.err.println("status code is invalid: "+ code);
					throw new Exception(response.getStatusLine().getReasonPhrase());
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				response.close();
			}		

	}
 
Example 19
Source File: HttpUtil.java    From database-transform-tool with Apache License 2.0 4 votes vote down vote up
/**
 * @param url 请求URL
 * @param method 请求URL
 * @param param	json参数(post|put)
 * @return
 */
public static String urlRequest(String url,String method,String param,String auth){
	String result = null;
	try {
		HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
		connection.setConnectTimeout(60*1000);
		connection.setRequestMethod(method.toUpperCase());
		if(auth!=null&&!"".equals(auth)){
			String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
			connection.setRequestProperty("Authorization", authorization);
		}
		if(param!=null&&!"".equals(param)){
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();
			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			dos.write(param.getBytes(Consts.UTF_8));
			dos.flush();
			dos.close();
		}else{
			connection.connect();
		}
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
			InputStream in = connection.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=in.read(buff, 0, buff.length))>0){
				out.write(buff, 0, len);
			}
			byte[] data = out.toByteArray();
			in.close();
			result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
		}else{
			result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
		}
		connection.disconnect();
	}catch (Exception e) {
		logger.error("--http request error !",e);
	}
	return result;
}
 
Example 20
Source File: WxMpTemplateMsgSender.java    From WePush with MIT License 4 votes vote down vote up
@Override
public SendResult asyncSend(String[] msgData) {
    SendResult sendResult = new SendResult();
    BoostForm boostForm = BoostForm.getInstance();

    try {
        if (PushControl.dryRun) {
            // 已成功+1
            PushData.increaseSuccess();
            boostForm.getSuccessCountLabel().setText(String.valueOf(PushData.successRecords));
            // 保存发送成功
            PushData.sendSuccessList.add(msgData);
            // 总进度条
            boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            String openId = msgData[0];
            WxMpTemplateMessage wxMessageTemplate = wxMpTemplateMsgMaker.makeMsg(msgData);
            wxMessageTemplate.setToUser(openId);

            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + wxMpService.getAccessToken();
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(wxMessageTemplate.toJson(), Consts.UTF_8);
            httpPost.setEntity(entity);
            if (wxMpService.getRequestHttp().getRequestHttpProxy() != null) {
                RequestConfig config = RequestConfig.custom().setProxy((HttpHost) wxMpService.getRequestHttp().getRequestHttpProxy()).build();
                httpPost.setConfig(config);
            }
            Future<HttpResponse> httpResponseFuture = getCloseableHttpAsyncClient().execute(httpPost, new CallBack(msgData));
            BoostPushRunThread.futureList.add(httpResponseFuture);
        }
    } catch (Exception e) {
        // 总发送失败+1
        PushData.increaseFail();
        boostForm.getFailCountLabel().setText(String.valueOf(PushData.failRecords));

        // 保存发送失败
        PushData.sendFailList.add(msgData);

        // 失败异常信息输出控制台
        ConsoleUtil.boostConsoleOnly("发送失败:" + e.toString() + ";msgData:" + JSONUtil.toJsonPrettyStr(msgData));
        // 总进度条
        boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());

        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(e.toString());
        return sendResult;
    }

    return sendResult;
}