下面列出了org.apache.http.impl.client.DefaultRedirectStrategy#org.apache.http.message.BasicNameValuePair 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void postLeaveInstance() {
AsyncCallbackPair<JSONObject> setInstanceCallback = new AsyncCallbackPair<JSONObject>(){
public void onSuccess(final JSONObject response) {
SetInstance("");
processInstanceLists(response);
FunctionCompleted("LeaveInstance");
}
public void onFailure(final String message) {
WebServiceError("LeaveInstance", message);
}
};
postCommandToGameServer(LEAVE_INSTANCE_COMMAND,
Lists.<NameValuePair>newArrayList(
new BasicNameValuePair(GAME_ID_KEY, GameId()),
new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress())),
setInstanceCallback);
}
/**
* This is how framework makes the KeyValue pair when "application/x-www-form-urlencoded" headers
* is passed in the request. In case you want to build or prepare the requests differently,
* you can override this method via @UseHttpClient(YourCustomHttpClient.class).
*
* @param httpUrl
* @param methodName
* @param reqBodyAsString
* @return
* @throws IOException
*/
public RequestBuilder createFormUrlEncodedRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) throws IOException {
RequestBuilder requestBuilder = RequestBuilder
.create(methodName)
.setUri(httpUrl);
if (reqBodyAsString != null) {
Map<String, Object> reqBodyMap = HelperJsonUtils.readObjectAsMap(reqBodyAsString);
List<NameValuePair> reqBody = new ArrayList<>();
for(String key : reqBodyMap.keySet()) {
reqBody.add(new BasicNameValuePair(key, reqBodyMap.get(key).toString()));
}
HttpEntity httpEntity = new UrlEncodedFormEntity(reqBody);
requestBuilder.setEntity(httpEntity);
requestBuilder.setHeader(CONTENT_TYPE, APPLICATION_FORM_URL_ENCODED);
}
return requestBuilder;
}
public static String getLiveVideoDataUrl(String channelType, String startDate, String endDate, String status, String hasPay, String order, String belongArea) {
List<BasicNameValuePair> list = new ArrayList();
list.add(new BasicNameValuePair("luamod", "main"));
list.add(new BasicNameValuePair("mod", "live"));
list.add(new BasicNameValuePair("ctl", "getChannelliveBystatus"));
list.add(new BasicNameValuePair(SocialConstants.PARAM_ACT, "index"));
list.add(new BasicNameValuePair(a.e, LetvConfig.getHKClientID()));
list.add(new BasicNameValuePair("beginDate", startDate));
list.add(new BasicNameValuePair("ct", channelType));
list.add(new BasicNameValuePair("endDate", endDate));
list.add(new BasicNameValuePair("status", status));
list.add(new BasicNameValuePair("belongArea", belongArea));
list.add(new BasicNameValuePair("order", order));
list.add(new BasicNameValuePair("hasPay", hasPay));
list.add(new BasicNameValuePair("pcode", LetvConfig.getPcode()));
list.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
return ParameterBuilder.getQueryUrl(list, getLiveHKDynamicUrl());
}
public static String getVideolistUrl(String aid, String vid, String page, String count, String o, String merge) {
String head = getStaticHead();
String end = LetvHttpApiConfig.getStaticEnd();
ArrayList<BasicNameValuePair> params = new ArrayList();
params.add(new BasicNameValuePair("mod", HOME_RECOMMEND_PARAMETERS.MOD_VALUE));
params.add(new BasicNameValuePair("ctl", "videolist"));
params.add(new BasicNameValuePair(SocialConstants.PARAM_ACT, "detail"));
params.add(new BasicNameValuePair("id", aid));
params.add(new BasicNameValuePair("vid", vid));
params.add(new BasicNameValuePair(PAGE.MYSHARE, page));
params.add(new BasicNameValuePair("s", count));
params.add(new BasicNameValuePair("o", o));
params.add(new BasicNameValuePair(PAGE.MYLETV, merge));
params.add(new BasicNameValuePair("pcode", LetvUtils.getPcode()));
params.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
return ParameterBuilder.getPathUrl(params, head, end);
}
/**
* 向目标url发送post请求
*
* @author sheefee
* @date 2017年9月12日 下午5:10:36
* @param url
* @param params
* @return boolean
*/
public static boolean post(String url, Map<String, String> params) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
// 参数处理
if (params != null && !params.isEmpty()) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8));
}
// 执行请求
try {
CloseableHttpResponse response = httpclient.execute(httpPost);
response.getStatusLine().getStatusCode();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Test
public void testDoPost201() throws IOException {
CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
HttpEntity entity = Mockito.mock(HttpEntity.class);
String data = "Sample Server Response";
Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_CREATED, "OK" ));
Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(entity);
Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);
HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
.build();
httpDriver.setHttpClient(httpClient);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("data", "value"));
String url = "https://localhost:4443/sample";
String out = httpDriver.doPost(url, params);
Assert.assertEquals(out, data);
}
/**
* 获取封禁原因列表
* @param bduss bduss
* @param tbName 贴吧名称
* @param uid 用户uid
* @return 封禁原因列表
*/
@SuppressWarnings("unchecked")
public List<String> prisionReasonList(String bduss, String tbName, String uid){
List<String> reasonList = null;
try {
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("BDUSS", bduss));
list.add(new BasicNameValuePair("_client_id", "wappc_1451451147094_870"));
list.add(new BasicNameValuePair("_client_type", "2"));
list.add(new BasicNameValuePair("_client_version", "6.2.2"));
list.add(new BasicNameValuePair("_phone_imei", "864587027315606"));
list.add(new BasicNameValuePair("forum_id", getFid(tbName)));
list.add(new BasicNameValuePair("user_id", uid));
list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
HttpResponse response = hk.execute(Constants.BAWU_POST_URL, createCookie(bduss), list);
String result = EntityUtils.toString(response.getEntity());
String code = (String) JsonKit.getInfo("error_code", result);
if("0".equals(code)){
reasonList = (List<String>) JsonKit.getInfo("reason", result);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return reasonList;
}
private HttpPost createWFSTransaction(
final HttpClient httpclient,
final String version,
final BasicNameValuePair... paramTuples) throws Exception {
final HttpPost command = new HttpPost(WFS_URL_PREFIX + "/Transaction");
final ArrayList<BasicNameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("version", version));
postParameters.add(
new BasicNameValuePair("typename", ServicesTestEnvironment.TEST_WORKSPACE + ":geostuff"));
Collections.addAll(postParameters, paramTuples);
command.setEntity(new UrlEncodedFormEntity(postParameters));
command.setHeader("Content-type", "text/xml");
command.setHeader("Accept", "text/xml");
return command;
}
@Test
public void testPostInStream() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/aaa");
final List<NameValuePair> values = new ArrayList<>();
values.add(new BasicNameValuePair("param1", "1"));
values.add(new BasicNameValuePair("param2", "2"));
values.add(new BasicNameValuePair("param3", "3"));
UrlEncodedFormEntity data = new UrlEncodedFormEntity(values, "UTF-8");
post.setEntity(data);
HttpResponse result = client.execute(post);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals(RESPONSE, response);
} finally {
client.getConnectionManager().shutdown();
}
}
/**
* Authenticates Dr. Elephant in Azkaban and sets the sessionId
*
* @param userName The username of the user
* @param password The password of the user
*/
@Override
public void login(String userName, String password) {
this._username = userName;
this._password = password;
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("action", "login"));
urlParameters.add(new BasicNameValuePair("username", userName));
urlParameters.add(new BasicNameValuePair("password", password));
try {
JSONObject jsonObject = fetchJson(urlParameters, _workflowExecutionUrl);
if (!jsonObject.has("session.id")) {
throw new RuntimeException("Login attempt failed. The session ID could not be obtained.");
}
this._sessionId = jsonObject.get("session.id").toString();
logger.debug("Session ID is " + this._sessionId);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Test(groups = {"Integration","Broken"})
public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
try {
Server server = useServerForTest(baseLauncher()
.forceUseOfDefaultCatalogWithJavaClassPath(true)
.withoutJsgui()
.start());
String appId = startAppAtNode(server);
String entityId = getTestEntityInApp(server, appId);
HttpClient client = HttpTool.httpClientBuilder()
.uri(getBaseUriRest())
.build();
List<? extends NameValuePair> nvps = Lists.newArrayList(
new BasicNameValuePair("arg", "bar"));
String effector = String.format("/applications/%s/entities/%s/effectors/identityEffector", appId, entityId);
HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUriRest() + effector),
ImmutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()),
URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes());
LOG.info("Effector response: {}", response.getContentAsString());
assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "response code=" + response.getResponseCode());
} finally {
LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in " + Time.makeTimeStringRounded(stopwatch));
}
}
/**
* Executes POST request on given URL with POST parameters and header
* parameters.
*/
private HttpEntity executePost(String url, String[][] postParams,
String[][] headerParams) throws IOException {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (String[] param : postParams) {
if (param[0] != null && param[1] != null) {
formparams.add(new BasicNameValuePair(param[0], param[1]));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
return executePost(url, entity, headerParams);
}
private void demo( String url ) throws IOException {
List<NameValuePair> parameters = new ArrayList<>();
parameters.add( new BasicNameValuePair( "user.name", "hdfs" ) );
parameters.add( new BasicNameValuePair( "jar", "wordcount/org.apache.hadoop-examples.jar" ) );
parameters.add( new BasicNameValuePair( "class", "org.apache.org.apache.hadoop.examples.WordCount" ) );
parameters.add( new BasicNameValuePair( "arg", "wordcount/input" ) );
parameters.add( new BasicNameValuePair( "arg", "wordcount/output" ) );
UrlEncodedFormEntity entity = new UrlEncodedFormEntity( parameters, StandardCharsets.UTF_8 );
HttpPost request = new HttpPost( url );
request.setEntity( entity );
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpResponse response = client.execute( request );
System.out.println( EntityUtils.toString( response.getEntity() ) );
}
/**
* 名人堂助攻
* @param bduss bduss
* @param tbName 贴吧名称
* @param tbs tbs
* @return 结果
* no=210009 //不在名人堂
* no=3110004 //暂未关注
* no=2280006 //已助攻
* no=0 //成功
*/
public String support(String bduss, String tbName, String tbs) {
String suportResult = "";
try {
HttpResponse hp = hk.execute(String.format(Constants.TIEBA_URL_HTTPS, tbName));
if(hp == null) {
hp = hk.execute(String.format(Constants.TIEBA_URL_HTTP, tbName));
}
String fidHtml= EntityUtils.toString(hp.getEntity());
String fid = StrKit.substring(fidHtml, "forum_id\":", ",");
String cookie = createCookie(bduss);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("forum_id", fid));
params.add(new BasicNameValuePair("tbs", tbs));
//3.获取npc_id
String result = EntityUtils.toString(hk.execute(Constants.GET_FORUM_SUPPORT, cookie, params).getEntity());
String npcId = JSONPath.eval(JSON.parse(result), "$.data[0].npc_info.npc_id").toString();
params.add(new BasicNameValuePair("npc_id", npcId));
//3.助攻
suportResult = EntityUtils.toString(hk.execute(Constants.FORUM_SUPPORT,cookie, params).getEntity());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return suportResult;
}
public String getPlayTraces(int updataId, String uid, String page, String pagesize, String sso_tk) {
String baseUrl = UrlConstdata.getDynamicUrl();
List<BasicNameValuePair> list = new ArrayList();
list.add(new BasicNameValuePair("mod", "minfo"));
list.add(new BasicNameValuePair("ctl", "cloud"));
list.add(new BasicNameValuePair(SocialConstants.PARAM_ACT, "get"));
list.add(new BasicNameValuePair("imei", LetvUtils.getIMEI()));
list.add(new BasicNameValuePair("mac", LetvUtils.getMacAddress()));
list.add(new BasicNameValuePair("uid", uid));
list.add(new BasicNameValuePair(MyDownloadActivityConfig.PAGE, page));
list.add(new BasicNameValuePair("pagesize", pagesize));
list.add(new BasicNameValuePair("sso_tk", sso_tk));
list.add(new BasicNameValuePair("pcode", LetvHttpApiConfig.PCODE));
list.add(new BasicNameValuePair("version", LetvHttpApiConfig.VERSION));
return ParameterBuilder.getQueryUrl(list, baseUrl);
}
/**
* 移除粉丝
* @param bduss bduss
* @param fans_uid 用户id
* @return 结果
*/
public String removeFans(String bduss, String fans_uid){
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("BDUSS", bduss));
list.add(new BasicNameValuePair("_client_id", "wappc_1542694366490_105"));
list.add(new BasicNameValuePair("_client_type", "2"));
list.add(new BasicNameValuePair("_client_version", "9.8.8.13"));
list.add(new BasicNameValuePair("fans_uid", fans_uid));
list.add(new BasicNameValuePair("tbs", getTbs(bduss)));
list.add(new BasicNameValuePair("timestamp", System.currentTimeMillis()+""));
list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
try {
HttpResponse response = hk.execute(Constants.REMOVE_FANS, null, list);
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return "";
}
/**
*
* @param Id
* @param Ver
* @return
* @throws PDException
*/
@Override
protected InputStream Retrieve(String Id, String Ver, Record Rec) throws PDException
{
VerifyId(Id);
CloseableHttpResponse response2 = null;
try {
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair(ORDER, DriverRemote.S_RETRIEVEFILE));
nvps.add(new BasicNameValuePair(DriverRemote.PARAM, "<OPD><Id>"+Id+"</Id><Ver>"+Ver+"</Ver></OPD>"));
UrlPost.setEntity(new UrlEncodedFormEntity(nvps));
response2 = httpclient.execute(UrlPost, context);
HttpEntity Resp=response2.getEntity();
return(Resp.getContent());
} catch (Exception ex)
{
PDException.GenPDException("Error_retrieving_content", ex.getLocalizedMessage());
}
return (null);
}
private static List<NameValuePair> convertParameters(final Map<String, List<String>> parameterMap) {
final List<NameValuePair> params = new ArrayList<>();
if (parameterMap == null) {
return params;
}
for (final Map.Entry<String, List<String>> param : parameterMap.entrySet()) {
final String key = param.getKey();
if(param.getValue() == null || param.getValue().isEmpty()) {
params.add(new BasicNameValuePair(key, null));
LOG.debug("key: " + key + "\tempty value");
}
for (final String value : param.getValue()) {
params.add(new BasicNameValuePair(key, value));
LOG.debug("key: "+ key +"\tvalue: " + value);
}
}
return params;
}
private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException {
final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
List<NameValuePair> formParams = new ArrayList<>();
postVariables.forEach((name, values) -> values.forEach(value -> {
if (multipart) {
if (value.startsWith("@")) {
File f = new File(value.substring(1));
multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName());
} else {
multipartBuilder.addTextBody(name, value);
}
} else {
formParams.add(new BasicNameValuePair(name, value));
}
}));
if (multipart) {
request.setEntity(multipartBuilder.build());
} else {
request.setEntity(new UrlEncodedFormEntity(formParams));
}
}
public static String getAlbumVideoInfoUrl(String aid) {
String head = getStaticHead();
String end = LetvHttpApiConfig.getStaticEnd();
ArrayList<BasicNameValuePair> params = new ArrayList();
params.add(new BasicNameValuePair("mod", HOME_RECOMMEND_PARAMETERS.MOD_VALUE));
params.add(new BasicNameValuePair("ctl", "album"));
params.add(new BasicNameValuePair("id", aid));
params.add(new BasicNameValuePair(SocialConstants.PARAM_ACT, "detail"));
params.add(new BasicNameValuePair("pcode", LetvUtils.getPcode()));
params.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
return ParameterBuilder.getPathUrl(params, head, end);
}
/**
* multipart/mixed post请求
*
* @param url
* @param paramsList
* @return
* @throws Exception
*/
public static String doPostByMultipartMixed(String url, List<CustomHttpParams> paramsList) throws Exception {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--";
String LINEND = "\r\n";
if (null == paramsList || paramsList.isEmpty()) {
return null;
}
byte[] totalByte = null;
String data = null;
int size = paramsList.size();
for (int i = 0; i < size; i++) {
CustomHttpParams httpParam = paramsList.get(i);
Map<String, Object> map = httpParam.getMap();
byte[] bt = httpParam.getBt();
String joinMapStr = joinParams(map);
byte[] mapBt = joinMapStr.getBytes("UTF-8");
if (0 == i) {
data = PREFIX + BOUNDARY + LINEND + "Content-Type:application/octet-stream" + LINEND + "Content-Disposition:param;" + joinMapStr + LINEND + "Content-Length:" + mapBt.length + LINEND + LINEND;
totalByte = byteMerge(data.getBytes(), bt);
} else {
data = LINEND + PREFIX + BOUNDARY + LINEND + "Content-Type:application/octet-stream" + LINEND + "Content-Disposition:param;" + joinMapStr + LINEND + "Content-Length:" + mapBt.length + LINEND + LINEND;
totalByte = byteMerge(totalByte, data.getBytes());
totalByte = byteMerge(totalByte, bt);
}
}
data = LINEND + PREFIX + BOUNDARY + PREFIX;
totalByte = byteMerge(totalByte, data.getBytes());
NameValuePair nameValuePair = new BasicNameValuePair("boundary", BOUNDARY);
HttpEntity entity = Request.Post(url).connectTimeout(5000)
.bodyByteArray(totalByte, ContentType.create("multipart/mixed", nameValuePair))
.execute().returnResponse().getEntity();
return EntityUtils.toString(entity, "utf-8");
}
/**
* https post请求
* @param url
* @param formParamMap
* @return
*/
public static String doPostHttps(String url,Map<String, String> formParamMap) throws Exception {
initSSLContext();
HttpPost post = new HttpPost(url);
StringBuilder stringBuilder = new StringBuilder();
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
if(formParamMap !=null){
for(Map.Entry<String, String> entity: formParamMap.entrySet()){
nameValuePairList.add(new BasicNameValuePair(entity.getKey(), entity.getValue())) ;
}
}
post.setEntity(new UrlEncodedFormEntity(nameValuePairList, HermesConstants.CHARSET_UTF8));
HttpResponse response = httpClient.execute(post);
HttpEntity respEntity = response.getEntity();
int responseCode = response.getStatusLine().getStatusCode();
Logger.info("httpClient post 响应状态responseCode="+responseCode+", 请求 URL="+url);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(respEntity.getContent(), "UTF-8"));
String text = null;
if(responseCode == RSP_200 || responseCode == RSP_400){
while ((text = bufferedReader.readLine()) != null) {
stringBuilder.append(text);
}
}else{
throw new Exception("接口请求异常:接口响应状态="+responseCode);
}
bufferedReader.close();
post.releaseConnection();
return stringBuilder.toString();
}
public static String getLiveWatchNumUrl(String id) {
List<BasicNameValuePair> list = new ArrayList();
list.add(new BasicNameValuePair("id", id));
list.add(new BasicNameValuePair("group", "zhibo"));
list.add(new BasicNameValuePair("pcode", LetvConfig.getPcode()));
list.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
return ParameterBuilder.getQueryUrl(list, getLiveWatchNumHost());
}
void checkLoggedIn() {
synchronized (loggedIn) {
if (loggedIn.get()) {
return;
}
HttpPost loginRequest = new HttpPost("https://secure.nicovideo.jp/secure/login");
loginRequest.setEntity(new UrlEncodedFormEntity(Arrays.asList(
new BasicNameValuePair("mail", email),
new BasicNameValuePair("password", password)
), StandardCharsets.UTF_8));
try (HttpInterface httpInterface = getHttpInterface()) {
try (CloseableHttpResponse response = httpInterface.execute(loginRequest)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 302) {
throw new IOException("Unexpected response code " + statusCode);
}
Header location = response.getFirstHeader("Location");
if (location == null || location.getValue().contains("message=")) {
throw new FriendlyException("Login details for NicoNico are invalid.", COMMON, null);
}
loggedIn.set(true);
}
} catch (IOException e) {
throw new FriendlyException("Exception when trying to log into NicoNico", SUSPICIOUS, e);
}
}
}
public boolean login(UserModel userModel) {
HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userModel.getUsername());
HttpPost httpPost = new HttpPost(apiConfig.getLogin());
List<NameValuePair> formparams = new ArrayList<>();
formparams.add(new BasicNameValuePair("username", userModel.getUsername()));
formparams.add(new BasicNameValuePair("password", userModel.getPassword()));
formparams.add(new BasicNameValuePair("appid", "otn"));
formparams.add(new BasicNameValuePair("answer", userModel.getAnswer()));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
Consts.UTF_8);
httpPost.setEntity(urlEncodedFormEntity);
String response = httpUtil.post(httpPost);
if (StringUtils.isEmpty(response)) {
log.error("登录失败!");
return false;
}
Gson jsonResult = new Gson();
Map rsmap = jsonResult.fromJson(response, Map.class);
if (!"0.0".equals(rsmap.getOrDefault("result_code", "").toString())) {
log.error("登陆失败:{}", rsmap);
return false;
}
UserTicketStore.httpUtilStore.put(userModel.getUsername(), httpUtil);
userModel.setUamtk(rsmap.get("uamtk").toString());
return true;
}
public String getChannelSiftListUrl() {
List<BasicNameValuePair> params = new ArrayList();
params.add(new BasicNameValuePair("uid", PreferencesManager.getInstance().isLogin() ? PreferencesManager.getInstance().getUserId() : ""));
params.add(new BasicNameValuePair(HOME_RECOMMEND_PARAMETERS.DEVICEID_KEY, LetvUtils.generateDeviceId(BaseApplication.getInstance())));
params.add(new BasicNameValuePair("pcode", LetvConfig.getPcode()));
params.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
return ParameterBuilder.getQueryUrl(params, getFilterHeader(LetvUtils.isInHongKong()));
}
void checkLoggedIn() {
synchronized (loggedIn) {
if (loggedIn.get()) {
return;
}
HttpPost loginRequest = new HttpPost("https://secure.nicovideo.jp/secure/login");
loginRequest.setEntity(new UrlEncodedFormEntity(Arrays.asList(
new BasicNameValuePair("mail", email),
new BasicNameValuePair("password", password)
), StandardCharsets.UTF_8));
try (HttpInterface httpInterface = getHttpInterface()) {
try (CloseableHttpResponse response = httpInterface.execute(loginRequest)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 302) {
throw new IOException("Unexpected response code " + statusCode);
}
Header location = response.getFirstHeader("Location");
if (location == null || location.getValue().contains("message=")) {
throw new FriendlyException("Login details for NicoNico are invalid.", COMMON, null);
}
loggedIn.set(true);
}
} catch (IOException e) {
throw new FriendlyException("Exception when trying to log into NicoNico", SUSPICIOUS, e);
}
}
}
@SuppressWarnings("unused")
private static List<NameValuePair> getPostParameterPairs(Map<String, String> postParams) {
List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size());
for (String key : postParams.keySet()) {
result.add(new BasicNameValuePair(key, postParams.get(key)));
}
return result;
}
/**
* 执行post请求
*
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public HttpResult doPost(String url, Map<String, String> paramMap) throws IOException {
HttpPost httpPost = new HttpPost(url);
// httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//设置请求参数
httpPost.setConfig(requestConfig);
if (paramMap != null) {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String s : paramMap.keySet()) {
parameters.add(new BasicNameValuePair(s, paramMap.get(s)));
}
//构建一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"));
//将请求实体放入到httpPost中
httpPost.setEntity(formEntity);
}
//创建httpClient对象
CloseableHttpResponse response = null;
try {
//执行请求
response = httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8"));
} finally {
if (response != null) {
response.close();
}
}
}
protected HttpEntity buildsimple() throws HTTPException {
List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, Field> mapentry : parts.entrySet()) {
Field field = mapentry.getValue();
params.add(new BasicNameValuePair(field.fieldname, field.value.toString()));
}
try {
return new UrlEncodedFormEntity(params);
} catch (UnsupportedEncodingException e) {
return null;
}
}