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"}