各种语言使用HTTP Request

本文介绍了如何使用Java和C++实现HTTP请求。Java部分展示了如何设置JSON类型的POST请求,包括设置请求头和编码方式。C++部分详细演示了通过WinHTTP API进行GET请求的过程,包括初始化会话、连接服务器、发送请求及接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. JAVA
String requestContent = "{"id":"1","sort":"des","number":"9","startIndex":"1"}";
try {
           StringEntity entity = new StringEntity(requestContent);
           entity.setContentEncoding("UTF-8");
           entity.setContentType("application/json"); //set the request content type as JSON
           httpPost.setEntity(entity);
} catch (UnsupportedEncodingException e1) {
           e1.printStackTrace();
}
httpResponse=httpClient.execute(httpPost);

2.C++
实现Http访问,微软提供了二套API:WinINet, WinHTTP, 他们实现Http访问的流程一致:
1, 首先我们打开一个Session获得一个HINTERNET session句柄;
2, 然后我们使用这个session句柄与服务器连接得到一个HINTERNET connect句柄;
3, 然后我们使用这个connect句柄来打开Http 请求得到一个HINTERNET request句柄;
4, 这时我们就可以使用这个request句柄来发送数据与读取从服务器返回的数据;
5, 最后依次关闭request,connect,session句柄。
#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include <crtdbg.h>
#include <string>
#include <winhttp.h>
#pragma comment(lib, "winhttp")
using namespace std;
 
void do_work(string strUrl);
int _tmain(int argc, _TCHAR* argv[])
{
    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
    do_work("https://albert.apple.com/WebObjects/ALUnbrick.woa/wa/deviceActivation?device=MacOS");
    system("pause");
}
 
void do_work(string strUrl)
{
    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL bResults = FALSE;
    HINTERNET hSession = NULL, 
              hConnect = NULL, 
              hRequest = NULL;
    //get the proxy
    WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig = { 0 };
    if (!::WinHttpGetIEProxyConfigForCurrentUser(&ieProxyConfig))
    {
        // Call GetLastError for error information.
        cout << "Error in getting proxy..." << endl;
    }
    WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions = { 0 };
    if(ieProxyConfig.fAutoDetect)
    {
        autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
        autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP |        WINHTTP_AUTO_DETECT_TYPE_DNS_A;
    }
 
    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"A WinHTTP Example Program/1.0", 
                           WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, 
                           WINHTTP_NO_PROXY_NAME, 
                           WINHTTP_NO_PROXY_BYPASS, 0);
 
    // Specify an HTTP server
    if (hSession)
        hConnect = WinHttpConnect(hSession, L"baidu.com", 
                                  INTERNET_DEFAULT_HTTP_PORT, 0);
   
 
    // Create an HTTP Request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"GET", 
                                      L"", //requestStr
                                      NULL, WINHTTP_NO_REFERER, 
                                      WINHTTP_DEFAULT_ACCEPT_TYPES, 
                                      0);
 
    // Send a Request.
    if (hRequest)
        bResults = WinHttpSendRequest(hRequest, 
                                      WINHTTP_NO_ADDITIONAL_HEADERS, 
                                      0, WINHTTP_NO_REQUEST_DATA, 0, 
                                      0, 0);
 
    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);
 
    // Continue to verify data until there is nothing left.
    if (bResults)
    {
        do
        {
            // Verify available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n", 
                       GetLastError());
            
            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize+1];
            
            // Read the Data.
            ZeroMemory(pszOutBuffer, dwSize+1);
 
            if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, 
                                 dwSize, &dwDownloaded))
                printf("Error %u in WinHttpReadData.\n", GetLastError());
            else
                printf("%s\n", pszOutBuffer);
 
            // Free the memory allocated to the buffer.
            delete[] pszOutBuffer;
        } while (dwSize > 0);
    } 
 
    // Report errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());
 
    // Close open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
}

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/4607594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值