Java Code Examples for org.apache.http.NameValuePair

The following examples show how to use org.apache.http.NameValuePair. 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: java-Crawler   Source File: MyClawer.java    License: MIT License 6 votes vote down vote up
public static synchronized void printHot(String u) throws Exception {
    HttpHost httpHost = new HttpHost( "60.195.17.240",3128);
    HttpPost httpPost = new HttpPost(u);
    httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36");
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("params", "RlBC7U1bfy/boPwg9ag7/a7AjkQOgsIfd+vsUjoMY2tyQCPFgnNoxHeCY+ZuHYqtM1zF8DWIBwJWbsCOQ6ZYxBiPE3bk+CI1U6Htoc4P9REBePlaiuzU4M3rDAxtMfNN3y0eimeq3LVo28UoarXs2VMWkCqoTXSi5zgKEKbxB7CmlBJAP9pn1aC+e3+VOTr0"));
    list.add(new BasicNameValuePair("encSecKey", "76a0d8ff9f6914d4f59be6b3e1f5d1fc3998317195464f00ee704149bc6672c587cd4a37471e3a777cb283a971d6b9205ce4a7187e682bdaefc0f225fb9ed1319f612243096823ddec88b6d6ea18f3fec883d2489d5a1d81cb5dbd0602981e7b49db5543b3d9edb48950e113f3627db3ac61cbc71d811889d68ff95d0eba04e9"));
    httpPost.setEntity(new UrlEncodedFormEntity(list));
    CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String ux = EntityUtils.toString(entity, "utf-8");
    //System.out.println(ux);
    ArrayList<String> s = getBook(ux);
    if(s.size()!=0) {
        System.out.println(Thread.currentThread().getName() + " :::   " + "目标:" + u);
        randomAccessFile.write((Thread.currentThread().getName() + " :::   " + "目标:" + u+"\r\n").getBytes());
    }
    for (int i = 0; i < s.size(); i++) {
        String[] arr = s.get(i).split("\"");
        System.out.println("              "+arr[2]);
        randomAccessFile.write((arr[2]+"\r\n").getBytes());
    }
}
 
Example 2
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 3
public static void loginUploadBox() throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setParameter(
            "http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);

    System.out.println("Trying to log in to uploadbox.com");
    HttpPost httppost = new HttpPost("http://www.uploadbox.com/en");
    httppost.setHeader("Cookie", sidcookie);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("login", ""));
    formparams.add(new BasicNameValuePair("passwd", ""));
    formparams.add(new BasicNameValuePair("ac", "auth"));
    formparams.add(new BasicNameValuePair("back", ""));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    httppost.setEntity(entity);
    HttpResponse httpresponse = httpclient.execute(httppost);
    HttpEntity resEntity = httpresponse.getEntity();
    System.out.println(httpresponse.getStatusLine());

}
 
Example 4
Source Project: rya   Source File: SmartUriAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private static IRI createTypePropertiesUri(final ImmutableMap<RyaIRI, ImmutableMap<RyaIRI, Property>> typeProperties) throws SmartUriException {
    final List<NameValuePair> nameValuePairs = new ArrayList<>();
    for (final Entry<RyaIRI, ImmutableMap<RyaIRI, Property>> typeProperty : typeProperties.entrySet()) {
        final RyaIRI type = typeProperty.getKey();
        final Map<RyaIRI, Property> propertyMap = typeProperty.getValue();
        final IRI typeUri = createIndividualTypeWithPropertiesUri(type, propertyMap);
        final String keyString = type.getDataType().getLocalName();
        final String valueString = typeUri.getLocalName();
        nameValuePairs.add(new BasicNameValuePair(keyString, valueString));
    }

    final URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.addParameters(nameValuePairs);

    String uriString;
    try {
        final java.net.URI uri = uriBuilder.build();
        final String queryString = uri.getRawSchemeSpecificPart();
        uriString = "urn:test" + queryString;
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to create type properties for the Smart URI", e);
    }

    return VF.createIRI(uriString);
}
 
Example 5
Source Project: ticket   Source File: ApiRequestService.java    License: 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 6
Source Project: android-advanced-light   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void useHttpClientPost(String url) {
    HttpPost mHttpPost = new HttpPost(url);
    mHttpPost.addHeader("Connection", "Keep-Alive");
    try {
        HttpClient mHttpClient = createHttpClient();
        List<NameValuePair> postParams = new ArrayList<>();
        //要传递的参数
        postParams.add(new BasicNameValuePair("ip", "59.108.54.37"));
        mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
        HttpEntity mHttpEntity = mHttpResponse.getEntity();
        int code = mHttpResponse.getStatusLine().getStatusCode();
        if (null != mHttpEntity) {
            InputStream mInputStream = mHttpEntity.getContent();
            String respose = converStreamToString(mInputStream);
            Log.d(TAG, "请求状态码:" + code + "\n请求结果:\n" + respose);
            mInputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: Explorer   Source File: ExplorerWebSocketServer.java    License: Apache License 2.0 6 votes vote down vote up
private String postQueryDatavis(String query) throws IOException {
    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://localhost:9000/dataviews");
    String responseString = "";
    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("name", query));
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("iDataSource", "1"));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            responseString = IOUtils.toString(instream);
        } finally {
            instream.close();
        }
    }

    return responseString;
}
 
Example 8
Source Project: Klyph   Source File: APKExpansionPolicy.java    License: MIT License 6 votes vote down vote up
private Map<String, String> decodeExtras(String extras) {
    Map<String, String> results = new HashMap<String, String>();
    try {
        URI rawExtras = new URI("?" + extras);
        List<NameValuePair> extraList = URLEncodedUtils.parse(rawExtras, "UTF-8");
        for (NameValuePair item : extraList) {
            String name = item.getName();
            int i = 0;
            while (results.containsKey(name)) {
                name = item.getName() + ++i;
            }
            results.put(name, item.getValue());
        }
    } catch (URISyntaxException e) {
        Log.w(TAG, "Invalid syntax error while decoding extras data from server.");
    }
    return results;
}
 
Example 9
Source Project: web-sso   Source File: LogoutAppServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 请求某个URL,带着参数列表。
 * @param url
 * @param nameValuePairs
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
protected String requestUrl(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException {
	HttpPost httpPost = new HttpPost(url);
	if(nameValuePairs!=null && nameValuePairs.size()>0){
		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	}
	CloseableHttpResponse response = httpClient.execute(httpPost);  
	try {  
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			String content = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
			return content;
		}
		else{
			logger.warn("request the url: "+url+" , but return the status code is "+response.getStatusLine().getStatusCode());
			return null;
		}
	}
	finally{
		response.close();
	}
}
 
Example 10
Source Project: BigApp_Discuz_Android   Source File: URLEncodedUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds all parameters within the Scanner to the list of <code>parameters</code>.
 * For example,a scanner containing the string <code>a=1&b=2&c=3</code> would
 * add the {@link org.apache.http.NameValuePair NameValuePairs} a=1, b=2, and c=3 to the
 * list of parameters.
 *
 * @param parameters List to add parameters to.
 * @param scanner    Input that contains the parameters to parse.
 */
public static void parse(
        final List<NameValuePair> parameters,
        final Scanner scanner) {
    scanner.useDelimiter(PARAMETER_SEPARATOR);
    while (scanner.hasNext()) {
        String name = null;
        String value = null;
        String token = scanner.next();
        int i = token.indexOf(NAME_VALUE_SEPARATOR);
        if (i != -1) {
            name = token.substring(0, i).trim();
            value = token.substring(i + 1).trim();
        } else {
            name = token.trim();
        }
        parameters.add(new BasicNameValuePair(name, value));
    }
}
 
Example 11
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 12
Source Project: extract   Source File: RESTSpewer.java    License: MIT License 6 votes vote down vote up
@Override
public void write(final TikaDocument tikaDocument) throws IOException {
	final HttpPut put = new HttpPut(uri.resolve(tikaDocument.getId()));
	final List<NameValuePair> params = new ArrayList<>();

	params.add(new BasicNameValuePair(fields.forId(), tikaDocument.getId()));
	params.add(new BasicNameValuePair(fields.forPath(), tikaDocument.getPath().toString()));
	params.add(new BasicNameValuePair(fields.forText(), toString(tikaDocument.getReader())));

	if (outputMetadata) {
		parametrizeMetadata(tikaDocument.getMetadata(), params);
	}

	put.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
	put(put);
}
 
Example 13
Source Project: raccoon4   Source File: Identity.java    License: Apache License 2.0 6 votes vote down vote up
private static Map<String, String> doPost(HttpClient client,
		List<NameValuePair> params) throws ClientProtocolException,
		 IOException {
	HttpPost httppost = new HttpPost(LOGIN_URL);
	httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
	HttpResponse response = client.execute(httppost);
	Map<String, String> map = parseContent(response.getEntity().getContent());
	if (response.getStatusLine().getStatusCode() == 200) {
		return map;
	}

	if (map.containsKey("Error")) {
		throw new ClientProtocolException(map.get("Error"));
	}
	throw new HttpResponseException(response.getStatusLine().getStatusCode(),
			response.getStatusLine().getReasonPhrase());
}
 
Example 14
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 15
Source Project: ZTuoExchange_framework   Source File: CaiPiaoHttpUtils.java    License: MIT License 6 votes vote down vote up
/**
 * post form
 * 
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param bodys
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		Map<String, String> bodys)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPost request = new HttpPost(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (bodys != null) {
           List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

           for (String key : bodys.keySet()) {
               nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
           }
           UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
           formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
           request.setEntity(formEntity);
       }

       return httpClient.execute(request);
   }
 
Example 16
Source Project: charging_pile_cloud   Source File: AliHttpUtils.java    License: MIT License 6 votes vote down vote up
/**
 * post form
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param bodys
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  Map<String, String> bodys)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (bodys != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

        for (String key : bodys.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
        formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
        request.setEntity(formEntity);
    }

    return httpClient.execute(request);
}
 
Example 17
/**
 * Use this method to publish using POST.
 * @param payload - use the buildPayload method to retrieve NameValuePair to use as payload here.
 * @param userAgent - set the userAgent - this can be overridden if userAgentOverride (ua) is set in payload
 * @param useSSL - to publish using HTTPS, set this value to true.
 * @return
 */
public static boolean publishPOST(List<NameValuePair> payload, String userAgent, boolean useSSL) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(getURI(useSSL));
    post.setHeader(GoogleAnalyticsConstants.HTTP_HEADER_USER_AGENT, userAgent);

    try {
        post.setEntity(new UrlEncodedFormEntity(payload));
        HttpResponse response = client.execute(post);

        if((response.getStatusLine().getStatusCode() == 200)
                && (response.getFirstHeader(GoogleAnalyticsConstants.HTTP_HEADER_CONTENT_TYPE).getValue()
                .equals(GoogleAnalyticsConstants.RESPONSE_CONTENT_TYPE))) {
            return true;
        }
        return false;
    } catch (IOException e) {
        return false;
    }
}
 
Example 18
Source Project: sylph   Source File: WebAppProxyServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected void doGet1(HttpServletRequest req, HttpServletResponse resp)
        throws IOException
{
    try {
        final String remoteUser = req.getRemoteUser();
        final String pathInfo = req.getPathInfo();

        String[] parts = pathInfo.split("/", 3);
        checkArgument(parts.length >= 2, remoteUser + " gave an invalid proxy path " + pathInfo);
        //parts[0] is empty because path info always starts with a /
        String jobIdOrRunId = parts[1];
        String rest = parts.length > 2 ? parts[2] : "";

        URI trackingUri = new URI(getJobUrl(jobIdOrRunId));

        // Append the user-provided path and query parameter to the original
        // tracking url.
        String query = req.getQueryString() == null ? "" : req.getQueryString();
        List<NameValuePair> queryPairs = URLEncodedUtils.parse(query, null);
        UriBuilder builder = UriBuilder.fromUri(trackingUri);
        for (NameValuePair pair : queryPairs) {
            builder.queryParam(pair.getName(), pair.getValue());
        }
        URI toFetch = builder.path(rest).build();

        proxyLink(req, resp, toFetch, null);
    }
    catch (URISyntaxException e) {
        throw new IOException(e);
    }
}
 
Example 19
Source Project: BigApp_Discuz_Android   Source File: URIBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds parameter to URI query. The parameter name and value are expected to be unescaped
 * and may contain non ASCII characters.
 */
public URIBuilder addParameter(final String param, final String value) {
    if (this.queryParams == null) {
        this.queryParams = new ArrayList<NameValuePair>();
    }
    this.queryParams.add(new BasicNameValuePair(param, value));
    this.encodedQuery = null;
    this.encodedSchemeSpecificPart = null;
    return this;
}
 
Example 20
Source Project: QuickSDK   Source File: U8HttpUtils.java    License: MIT License 5 votes vote down vote up
public static String httpGet(String url, Map<String, String> params){
	
	List<NameValuePair> lst = new ArrayList<NameValuePair>();
	if(params != null){
		Iterator<String> keyItors = params.keySet().iterator();
		while(keyItors.hasNext()){
			String key = keyItors.next();
			String val = params.get(key);
			lst.add(new BasicNameValuePair(key, val));
		}
	}
	
	return httpGet(url, lst);
}
 
Example 21
Source Project: emissary   Source File: WorkSpaceAdapter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Outbound open tells a remote WorkSpace to start pulling data
 * 
 * @param place the remote place to contact
 * @param space the location of the work distributor
 */
public EmissaryResponse outboundOpenWorkSpace(final String place, final String space) {

    final String placeUrl = KeyManipulator.getServiceHostURL(place);
    final HttpPost method = new HttpPost(placeUrl + CONTEXT + "/WorkSpaceClientOpenWorkSpace.action");

    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair(CLIENT_NAME, place));
    nvps.add(new BasicNameValuePair(SPACE_NAME, space));
    method.setEntity(new UrlEncodedFormEntity(nvps, java.nio.charset.Charset.defaultCharset()));
    // set a timeout in case a node is unresponsive
    method.setConfig(RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build());

    return send(method);
}
 
Example 22
Source Project: android-open-project-demo   Source File: URLEncodedUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as built from the
 * URI's query portion. For example, a URI of
 * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three
 * NameValuePairs, one for a=1, one for b=2, and one for c=3.
 * <p/>
 * This is typically useful while parsing an HTTP PUT.
 *
 * @param uri uri to parse
 */
public static List<NameValuePair> parse(final URI uri) {
    final String query = uri.getRawQuery();
    if (!TextUtils.isEmpty(query)) {
        List<NameValuePair> result = new ArrayList<NameValuePair>();
        Scanner scanner = new Scanner(query);
        parse(result, scanner);
        return result;
    } else {
        return Collections.emptyList();
    }
}
 
Example 23
Source Project: rya   Source File: SmartUriAdapter.java    License: Apache License 2.0 5 votes vote down vote up
private static IRI createIndividualTypeWithPropertiesUri(final RyaIRI type, final Map<RyaIRI, Property> map) throws SmartUriException {
    final List<NameValuePair> nameValuePairs = new ArrayList<>();
    for (final Entry<RyaIRI, Property> entry : map.entrySet()) {
        final RyaIRI key = entry.getKey();
        final Property property = entry.getValue();

        final RyaType ryaType = property.getValue();
        final String keyString = (VF.createIRI(key.getData())).getLocalName();
        final Value value = RyaToRdfConversions.convertValue(ryaType);
        final String valueString = value.stringValue();
        nameValuePairs.add(new BasicNameValuePair(keyString, valueString));
    }

    final URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.addParameters(nameValuePairs);

    String uriString;
    try {
        final java.net.URI uri = uriBuilder.build();
        final String queryString = uri.getRawSchemeSpecificPart();
        uriString = type.getData()/*VF.createIRI(type.getData()).getLocalName()*/ + queryString;
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to create type URI with all its properties for the Smart URI", e);
    }

    return VF.createIRI(uriString);
}
 
Example 24
Source Project: appinventor-extensions   Source File: GameClient.java    License: Apache License 2.0 5 votes vote down vote up
private void postServerCommand(final String command, final YailList arguments){
  AsyncCallbackPair<JSONObject> myCallback = new AsyncCallbackPair<JSONObject>() {
    public void onSuccess(final JSONObject result) {
      try {
        ServerCommandSuccess(command, JsonUtil.getListFromJsonArray(result.
            getJSONArray(MESSAGE_CONTENT_KEY), true));
      } catch (JSONException e) {
        Log.w(LOG_TAG, e);
        Info("Server command response failed to parse.");
      }
      FunctionCompleted("ServerCommand");
    }

    public void onFailure(String message) {
      ServerCommandFailure(command, arguments);
      WebServiceError("ServerCommand", message);
    }
  };

  Log.d(LOG_TAG, "Going to post " + command + " with args " + arguments);
  postCommandToGameServer(SERVER_COMMAND,
      Lists.<NameValuePair>newArrayList(
          new BasicNameValuePair(GAME_ID_KEY, GameId()),
          new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
          new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
          new BasicNameValuePair(COMMAND_TYPE_KEY, command),
          new BasicNameValuePair(COMMAND_ARGUMENTS_KEY, arguments.toJSONString())),
      myCallback);
}
 
Example 25
Source Project: ticket   Source File: ApiRequestService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean submitOrderRequest(BuyTicketInfoModel buyTicketInfoModel,
        TicketModel ticketModel) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore
            .get(buyTicketInfoModel.getUsername());
    SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    HttpPost httpPost = new HttpPost(apiConfig.getSubmitOrderRequest());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("back_train_date", shortSdf.format(cal.getTime())));
    formparams.add(new BasicNameValuePair("purpose_codes", "ADULT"));
    formparams.add(new BasicNameValuePair("query_from_station_name",
            Station.getNameByCode(buyTicketInfoModel.getTo())));
    formparams.add(new BasicNameValuePair("query_to_station_name",
            Station.getNameByCode(buyTicketInfoModel.getFrom())));
    formparams.add(new BasicNameValuePair("secretStr", ticketModel.getSecret()));
    formparams.add(new BasicNameValuePair("train_date", buyTicketInfoModel.getDate()));
    formparams.add(new BasicNameValuePair("tour_flag", "dc"));
    formparams.add(new BasicNameValuePair("undefined", ""));

    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 (null != rsmap.get("status") && rsmap.get("status").toString().equals("true")) {
        log.info("点击预定按钮成功");
        return true;

    } else if (null != rsmap.get("status") && rsmap.get("status").toString().equals("false")) {
        String errMsg = rsmap.get("messages") + "";
        log.error(errMsg);
    }
    return false;
}
 
Example 26
Source Project: webapp-hardware-bridge   Source File: BridgeWebSocketServer.java    License: MIT License 5 votes vote down vote up
private String getToken(List<NameValuePair> params) {
    for (NameValuePair pair : params) {
        if (pair.getName().equals("access_token")) {
            return pair.getValue();
        }
    }
    return null;
}
 
Example 27
Source Project: CrossBow   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 28
Source Project: android-open-project-demo   Source File: URIBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public List<NameValuePair> getQueryParams() {
    if (this.queryParams != null) {
        return new ArrayList<NameValuePair>(this.queryParams);
    } else {
        return new ArrayList<NameValuePair>();
    }
}
 
Example 29
Source Project: james-project   Source File: SerialiseToHTTP.java    License: Apache License 2.0 5 votes vote down vote up
private NameValuePair[] getNameValuePairs(String message) {

        int l = 1;
        if (parameterKey != null && parameterKey.length() > 0) {
            l = 2;
        }

        NameValuePair[] data = new BasicNameValuePair[l];
        data[0] = new BasicNameValuePair(messageKeyName, message);
        if (l == 2) {
            data[1] = new BasicNameValuePair(parameterKey, parameterValue);
        }

        return data;
    }
 
Example 30
public static NameValuePair getNovelIndex(int aid, LANG l) {
	// get full XML index of a novel, here is an example:
	// --------------------------------------------------
	// <?xml version="1.0" encoding="utf-8"?>
	// <package>
	// <volume vid="41748"><![CDATA[第一卷 告白于苍刻之夜]]>
	// <chapter cid="41749"><![CDATA[序章]]></chapter>
	// <chapter cid="41750"><![CDATA[第一章「去对我的『楯』说吧——」]]></chapter>
	// <chapter cid="41751"><![CDATA[第二章「我真的对你非常感兴趣」]]></chapter>
	// <chapter cid="41752"><![CDATA[第三章「揍我吧!」]]></chapter>
	// <chapter cid="41753"><![CDATA[第四章「下次,再来喝苹果茶」]]></chapter>
	// <chapter cid="41754"><![CDATA[第五章「这是约定」]]></chapter>
	// <chapter cid="41755"><![CDATA[第六章「你的背后——由我来守护!」]]></chapter>
	// <chapter cid="41756"><![CDATA[第七章「茱莉——爱交给你!」]]></chapter>
	// <chapter cid="41757"><![CDATA[尾声]]></chapter>
	// <chapter cid="41758"><![CDATA[后记]]></chapter>
	// <chapter cid="41759"><![CDATA[插图]]></chapter>
	// </volume>
	// <volume vid="45090"><![CDATA[第二卷 谎言、真相与赤红]]>
	// <chapter cid="45091"><![CDATA[序章]]></chapter>
	// <chapter cid="45092"><![CDATA[第一章「莉莉丝·布里斯托」]]></chapter>
	// <chapter cid="45093"><![CDATA[第二章「借你的话来说就是……」]]></chapter>
	// <chapter cid="45094"><![CDATA[第三章「这真是个好提议」]]></chapter>
	// <chapter cid="45095"><![CDATA[第四章「如守护骑士一般」]]></chapter>
	// <chapter cid="45096"><![CDATA[第五章「『咬龙战』,开始!」]]></chapter>
	// <chapter cid="45097"><![CDATA[第六章「超越人类的存在」]]></chapter>
	// <chapter cid="45098"><![CDATA[第七章「『灵魂』」]]></chapter>
	// <chapter cid="45099"><![CDATA[尾声]]></chapter>
	// <chapter cid="45100"><![CDATA[后记]]></chapter>
	// <chapter cid="45105"><![CDATA[插图]]></chapter>
	// </volume>
	// ...... ......
	// </package>
	return null;
}