将PHP curl请求转换为Java

时间:2018-11-22 18:34:59

标签: java php curl

所以我有这个PHP代码,它向指定的URL发出POST请求。 $ data数组用作应用于请求的过滤器(例如,显示第二页,该页面最多显示10个项目)。默认情况下,值是“ currentPage => 1”和“ itemsPerPage => 100”(我正在访问API)。

<?php

$usercode = '';
$username = '';
$password = '';
$URL = '';

$data =
    array (
        'currentPage' => 2,
        'itemsPerPage' => 10
    );

$hash = sha1(http_build_query($data) . sha1($password));

$requestData = array(
    'code' => $usercode,
    'username' => $username,
    'data' => $data,
    'hash' => $hash);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));

$result = curl_exec($ch);

$json_pretty = json_encode(json_decode($result), JSON_PRETTY_PRINT);
echo $json_pretty;

它与使用PHP语言完全一样,但我想在Java中实现相同的行为。问题在于过滤器不适用(对于每个请求,过滤器的值都会被忽略,而使用默认值)。我试图以与PHP中相同的形式发出请求,但是由于某些原因,过滤器不适用。这是我尝试使用Apache的HttpClient:

public class Foo
{
    private static String httpBuildQuery(List<? extends NameValuePair> parameters) {
        return URLEncodedUtils.format(parameters, "UTF-8").replace("*", "%2A");
    }

    public static void main(String[] args)
    {
        String username = "";
        String password = "";
        String usercode = "";
        final String URL = "";

        String headerValueToBeEncoded = username + ":" + password;
        String encodedHeaderValue = Base64.getEncoder().encodeToString(headerValueToBeEncoded.getBytes());

        List<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("currentPage", "2"));
        data.add(new BasicNameValuePair("itemsPerPage", "10"));

        String passwordHash = DigestUtils.sha1Hex(password);
        String dataQueryString = Foo.httpBuildQuery(data);
        String valueToBeHashed = dataQueryString + passwordHash;
        String hash = DigestUtils.sha1Hex(valueToBeHashed);

        List<NameValuePair> requestData = new ArrayList<>();
        requestData.add(new BasicNameValuePair("code", usercode));
        requestData.add(new BasicNameValuePair("username", username));
        requestData.add(new BasicNameValuePair("data", data.toString()));
        requestData.add(new BasicNameValuePair("hash", hash));

        String requestDataQueryString = Foo.httpBuildQuery(requestData);

        try (CloseableHttpClient client = HttpClientBuilder.create().build())
        {
            HttpPost request = new HttpPost(URL);
            request.setHeader("Authorization", "Basic " + encodedHeaderValue);
            request.setEntity(new StringEntity(requestDataQueryString));

            HttpResponse response = client.execute(request);

            BufferedReader bufReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuilder builder = new StringBuilder();
            String line;

            while ((line = bufReader.readLine()) != null)
            {
                builder.append(line);
                builder.append(System.lineSeparator());
            }

            JSONObject jsonObject = new JSONObject(builder.toString());
            JSONArray jsonArray = jsonObject.getJSONArray("results");

            for(int i=0; i < jsonArray.length(); i++)
            {
                System.out.println(jsonArray.getJSONObject(i).get("id"));
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

在此将预定义字符串(用户名,密码等)的值保留为空,因为它们包含敏感信息。在上一部分中,我仅打印了ID的值以检查是否已应用过滤器,但是对于每个请求,它都会打印100个ID。

0 个答案:

没有答案