Java Code Examples for org.apache.http.message.BasicNameValuePair

The following examples show how to use org.apache.http.message.BasicNameValuePair. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: appinventor-extensions   Source File: GameClient.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source Project: zerocode   Source File: BasicHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source Project: letv   Source File: LetvUrlMaker.java    License: Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 4
Source Project: letv   Source File: LetvUrlMaker.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
Source Project: simple-sso   Source File: HTTPUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 向目标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;
}
 
Example 6
Source Project: athenz   Source File: HttpDriverTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 7
Source Project: tieba-api   Source File: TieBaApi.java    License: MIT License 6 votes vote down vote up
/**
 * 获取封禁原因列表
 * @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;
}
 
Example 8
Source Project: geowave   Source File: GeoServerIT.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 9
Source Project: quarkus-http   Source File: ParameterEchoTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 10
Source Project: dr-elephant   Source File: AzkabanWorkflowClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example 11
@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));
    }
}
 
Example 12
Source Project: raccoon4   Source File: GooglePlayAPI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 13
Source Project: knox   Source File: TempletonDemo.java    License: Apache License 2.0 6 votes vote down vote up
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() ) );
}
 
Example 14
Source Project: tieba-api   Source File: TieBaApi.java    License: MIT License 6 votes vote down vote up
/**
 * 名人堂助攻
 * @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;
}
 
Example 15
Source Project: letv   Source File: PlayRecordApi.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 16
Source Project: tieba-api   Source File: TieBaApi.java    License: MIT License 6 votes vote down vote up
/**
 * 移除粉丝
 * @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 "";
}
 
Example 17
Source Project: openprodoc   Source File: StoreRem.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 *
 * @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); 
}
 
Example 18
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;
}
 
Example 19
Source Project: curly   Source File: ActionRunner.java    License: Apache License 2.0 6 votes vote down vote up
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));
    }
}
 
Example 20
Source Project: letv   Source File: LetvUrlMaker.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 21
Source Project: AthenaServing   Source File: CustomHttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 22
Source Project: hermes   Source File: HttpClientUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 23
Source Project: letv   Source File: LetvUrlMaker.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 24
Source Project: lavaplayer   Source File: NicoAudioSourceManager.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
  }
}
 
Example 25
Source Project: ticket   Source File: ApiRequestService.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 26
Source Project: letv   Source File: MediaAssetApi.java    License: Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example 27
Source Project: kyoko   Source File: NicoAudioSourceManager.java    License: MIT License 5 votes vote down vote up
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);
        }
    }
}
 
Example 28
Source Project: android-common-utils   Source File: HttpClientStack.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 29
Source Project: bbs   Source File: HttpClientManage.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 执行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();
        }
    }
}
 
Example 30
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;
  }
}
 
Example 31
Source Project: letv   Source File: LetvUrlMaker.java    License: Apache License 2.0 5 votes vote down vote up
public static String getPushUrl(String id, String msgId, String dev_id, String city) {
    String baseUrl = getPushBaseUrl();
    List<BasicNameValuePair> params = new ArrayList();
    params.add(new BasicNameValuePair("mod", "minfo"));
    params.add(new BasicNameValuePair("ctl", "pushmsg"));
    params.add(new BasicNameValuePair(SocialConstants.PARAM_ACT, "index"));
    params.add(new BasicNameValuePair("id", id));
    params.add(new BasicNameValuePair("msgid", msgId));
    params.add(new BasicNameValuePair("dev_id", dev_id));
    params.add(new BasicNameValuePair("city", city));
    params.add(new BasicNameValuePair("pcode", LetvConfig.getPcode()));
    params.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
    return ParameterBuilder.getQueryUrl(params, baseUrl);
}
 
Example 32
Source Project: keycloak   Source File: MutualTLSClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private OAuthClient.AccessTokenResponse getAccessTokenResponseWithQueryParams(String clientId, CloseableHttpClient client) throws Exception {
   OAuthClient.AccessTokenResponse token;// This is a very simplified version of
   HttpPost post = new HttpPost(oauth.getAccessTokenUrl() + "?client_id=" + clientId);
   List<NameValuePair> parameters = new LinkedList<>();
   parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
   parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, oauth.getCurrentQuery().get(OAuth2Constants.CODE)));
   parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, Charsets.UTF_8);
   post.setEntity(formEntity);

   return new OAuthClient.AccessTokenResponse(client.execute(post));
}
 
Example 33
Source Project: letv   Source File: MediaAssetApi.java    License: Apache License 2.0 5 votes vote down vote up
public String requestReplyListUrl(String commentId, int replyPage) {
    String baseUrl = getCombineHead() + "comment/replylist";
    ArrayList<BasicNameValuePair> list = new ArrayList();
    setCommonParams(list);
    list.add(new BasicNameValuePair("commentid", commentId));
    list.add(new BasicNameValuePair(MyDownloadActivityConfig.PAGE, String.valueOf(replyPage)));
    list.add(new BasicNameValuePair("rows", "20"));
    list.add(new BasicNameValuePair("source", "3"));
    return ParameterBuilder.getQueryUrl(list, baseUrl);
}
 
Example 34
Source Project: Discord4J   Source File: DiscordClient.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deletes a message with given ID from provided channel ID.
 *
 * @param messageID Message (ID) to delete.
 * @param channelID Channel to delete it from.
 * @throws IOException
 */
public void deleteMessage(String messageID, String channelID) throws IOException {
    if (this.isReady()) {
        try {
            Requests.DELETE.makeRequest(DiscordEndpoints.CHANNELS + channelID + "/messages/" + messageID,
                    new BasicNameValuePair("authorization", token));
        } catch (HTTP403Exception e) {
            Discord4J.logger.error("Received 403 error attempting to delete message; is your login correct?");
        }
    } else {
        Discord4J.logger.error("Bot has not signed in yet!");
    }
}
 
Example 35
Source Project: ha-bridge   Source File: SomfyInfo.java    License: Apache License 2.0 5 votes vote down vote up
public void login(String username, String password) throws Exception {

		initHttpClient();
		NameValue[] httpHeader = getHttpHeaders();
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("userId", username));
		nvps.add(new BasicNameValuePair("userPassword", password));
		log.debug("Making SOMFY http login call");
		UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvps);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		urlEncodedFormEntity.writeTo(bos);
		String body = bos.toString();
		String response = httpClient.doHttpRequest(BASE_URL + "json/login", HttpPost.METHOD_NAME, "application/x-www-form-urlencoded", body,httpHeader);
		log.debug("Somfy login response <<<{}>>>", response);
	}
 
Example 36
Source Project: carbon-device-mgt   Source File: JWTClient.java    License: Apache License 2.0 5 votes vote down vote up
public AccessTokenInfo getAccessTokenFromRefreshToken(String refreshToken, String username, String scopes,
													  String consumerKey, String consumerSecret)
		throws JWTClientException {
	List<NameValuePair> params = new ArrayList<>();
	params.add(new BasicNameValuePair(JWTConstants.GRANT_TYPE_PARAM_NAME, JWTConstants.REFRESH_TOKEN_GRANT_TYPE));
	params.add(new BasicNameValuePair(JWTConstants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken));
	params.add(new BasicNameValuePair(JWTConstants.SCOPE_PARAM_NAME, scopes));
	return getTokenInfo(params, consumerKey, consumerSecret);
}
 
Example 37
Source Project: AndroidProjects   Source File: OkApacheClientStack.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 38
Source Project: letv   Source File: LetvUrlMaker.java    License: Apache License 2.0 5 votes vote down vote up
public static String getLiveUrl(String channelId, boolean isPlay) {
    List<BasicNameValuePair> list = new ArrayList();
    list.add(new BasicNameValuePair("luamod", "main"));
    list.add(new BasicNameValuePair("mod", "live"));
    list.add(new BasicNameValuePair("ctl", TaskAddHttpRequest.stream));
    list.add(new BasicNameValuePair(SocialConstants.PARAM_ACT, "index"));
    list.add(new BasicNameValuePair(a.e, LetvConfig.getHKClientID()));
    list.add(new BasicNameValuePair("isPay", isPlay ? "1" : "0"));
    list.add(new BasicNameValuePair("withAllStreams", "1"));
    list.add(new BasicNameValuePair("channelId", channelId));
    list.add(new BasicNameValuePair("pcode", LetvConfig.getPcode()));
    list.add(new BasicNameValuePair("version", LetvUtils.getClientVersionName()));
    return ParameterBuilder.getQueryUrl(list, getLiveHKDynamicUrl());
}
 
Example 39
Source Project: quarkus-http   Source File: FormDataParserTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testCase() throws Exception {
    runTest(new BasicNameValuePair("name", "A Value"));
    runTest(new BasicNameValuePair("name", "A Value"), new BasicNameValuePair("Single-value", null));
    runTest(new BasicNameValuePair("name", "A Value"), new BasicNameValuePair("A/name/with_special*chars", "A $ value&& with=SomeCharacters"));
    runTest(new BasicNameValuePair("name", "A Value"), new BasicNameValuePair("Single-value", null), new BasicNameValuePair("A/name/with_special*chars", "A $ value&& with=SomeCharacters"));

}
 
Example 40
Source Project: emissary   Source File: HeartbeatManager.java    License: Apache License 2.0 5 votes vote down vote up
public static EmissaryResponse getHeartbeat(String fromPlace, String toPlace, EmissaryClient client) {
    final String directoryUrl = KeyManipulator.getServiceHostURL(toPlace);
    final HttpPost method = new HttpPost(directoryUrl + EmissaryClient.CONTEXT + "/Heartbeat.action");
    final String loc = KeyManipulator.getServiceLocation(toPlace);

    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair(HeartbeatAdapter.FROM_PLACE_NAME, fromPlace));
    nvps.add(new BasicNameValuePair(HeartbeatAdapter.TO_PLACE_NAME, loc));
    method.setEntity(new UrlEncodedFormEntity(nvps, java.nio.charset.Charset.defaultCharset()));

    return client.send(method);
}