You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java完成网关Digest认证登录后,如何正确发送JSON数据?

Hey there! Let's sort out that JSON sending problem you're facing. The issue with your current approach is two-fold: first, HttpGet isn't meant to carry a request body (that's what POST requests are for), and second, the way you're trying to attach the JSON uses deprecated/incorrect methods. Plus, your jsonSicuro string has a syntax error—let's fix all of that together.

Step 1: Switch to HttpPost for sending payloads

GET requests don't support request bodies in standard practice, so we'll use HttpPost instead of HttpGet to send your JSON data.

Step 2: Fix the JSON syntax

Your original JSON has a typo: it starts with ["txmsgid": (array syntax) but it's an object—should be {"txmsgid": ...}. Also, txmsgid is missing a value. Let's correct that first:

private static String jsonSicuro = "{\"txmsgid\": \"sample-tx-id\", \"trycount\": 5, \"port\": 2, \"payload\": \"01\", \"ack\": true, \"mote\": \"17A7F79\"}";

Step 3: Attach the JSON payload correctly

We'll create a StringEntity with your JSON, set the correct Content-Type header to application/json, and attach it to the HttpPost request.

Full Modified Code

Here's the updated version of your code with all fixes applied:

private static final String SPN_IP = "192.168.0.2";
private static final String SPN_LOGIN = "myadmin";
private static final String SPN_PASSWORD = "mypasswor";
// Fixed JSON syntax (object instead of array, added txmsgid value)
private static String jsonSicuro = "{\"txmsgid\": \"sample-tx-id\", \"trycount\": 5, \"port\": 2, \"payload\": \"01\", \"ack\": true, \"mote\": \"17A7F79\"}";

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, AuthenticationException, URISyntaxException {
    // SSL management (unchanged, works fine)
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // trust self-signed cert
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession sslSession) {
            return SPN_IP.equals(hostname); // validate the host name
        }
    });

    // Create client (unchanged)
    CloseableHttpClient httpclient = HttpClientBuilder.create()
            .setSSLSocketFactory(sslSocketFactory)
            .build();

    // --- Changed from HttpGet to HttpPost ---
    HttpPost httpPost = new HttpPost("https://" + SPN_IP);

    // HTTP digest auth (unchanged, this part works)
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("algorithm", "MD5");
    digestAuth.overrideParamter("realm", "https://" + SPN_IP);
    digestAuth.overrideParamter("nonce", Long.toString(new Random().nextLong(), 36));
    digestAuth.overrideParamter("qop", "auth");
    digestAuth.overrideParamter("nc", "0");
    digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());

    // Send HTTP digest header (unchanged)
    Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(SPN_LOGIN, SPN_PASSWORD), httpPost, null);
    System.out.println(auth.getName());
    System.out.println(auth.getValue());
    httpPost.setHeader(auth);

    // --- Add JSON payload ---
    // Create StringEntity with JSON, set correct content type
    StringEntity entity = new StringEntity(jsonSicuro, ContentType.APPLICATION_JSON);
    httpPost.setEntity(entity);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    System.out.println("Executing request: " + httpPost.getRequestLine());
    String response = httpclient.execute(httpPost, responseHandler);
    System.out.println("Response: " + response);
}

Key Notes:

  • Why HttpPost?: By HTTP standards, GET requests are for retrieving data, while POST is for sending data to the server (like your JSON payload). Most servers won't parse a request body from a GET request.
  • Content-Type Header: Setting ContentType.APPLICATION_JSON tells the gateway that you're sending JSON data, so it knows how to parse the payload correctly.
  • JSON Syntax: Always double-check your JSON—invalid syntax will cause the gateway to reject the request even if everything else is correct.

内容的提问来源于stack exchange,提问作者Nicola Carlucci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:51:36