0

I want to send a POST request with a JSON object to a specified URL, but it always failed.

I have already check every data to make sure they are correct, but when I send them, they seems to be changed, so that the destination server cannot process my request correctly.

 public static String translate(String query, String from, String to) {
    JSONObject response = new JSONObject();
    JSONObject request = new JSONObject();

    //Generate a random number
    int salt = getRandom();

    //Generate the sign
    String sign = encodeMD5Hex(APP_ID + query + salt + KEY);

    //Put all parameters into the request
    request.put("q", query);
    request.put("from", from);
    request.put("to", to);
    request.put("appid", APP_ID);
    request.put("salt", salt);
    request.put("sign", sign);

    return sendPOSTRequest(request);
}

private static String encodeMD5Hex(String data){
    return DigestUtils.md5Hex(data);
}

private static int getRandom() {
    return (int) ((Math.random() + 1) * 10000);
}

private static String sendPOSTRequest(JSONObject data) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<JSONObject> entity = new HttpEntity(data, headers);
    String answer = restTemplate.postForObject(BAIDU_TRANS_API_URL, entity, String.class);
    return answer;
}

I guess it's probably wrong in appid. Response always tell me I have a incorrect appid even I have 100% sure it's correct. And here is the format of appid parameter: name: appid type: INT But a 17 digits number's int is totally out of range.

Response: {"error_code":"52003","error_msg":"UNAUTHORIZED USER"}

Nick Lin
  • 1
  • 1
  • 4
  • Please provide the full response (or exception) in your question. – user871611 Feb 13 '19 at 11:26
  • Possible duplicate of [Call another rest api from my server in Spring-Boot](https://stackoverflow.com/questions/42365266/call-another-rest-api-from-my-server-in-spring-boot) – TongChen Feb 13 '19 at 11:30
  • What is the data type of your APP_ID? if its 17 digits, why not declare it as Long instead of Int. Anyway JSON object only has Number as datatype so Int or Long it will go same way. – Arpit Agrawal Feb 13 '19 at 11:33
  • 1
    You should let Spring inject the properly-configured RestTemplate, not make a new one for every request. – OrangeDog Feb 13 '19 at 11:37

1 Answers1

0

JSONObject will accept value of type object so you can convert the appId value to long or any other data types that is accepted in the remote http call.