我正在尝试使用apache httpClient调用应用程序,并且收到406响应,我已经设置了userAgent和accept标头,但是问题仍然存在。
但是使用java.net.HttpURLConnection的另一个代码可以调用具有相同有效负载的相同URL。
如果有人能向我指出apache客户端代码到底有什么问题,我将不胜感激,下面将发布这两个代码。
Apache客户端
public static JSONObject doPayment(String authorization, String signature, String nonce,String timestamp)
{
JSONObject resp = new JSONObject();
DateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
try {
int CONNECTION_TIMEOUT = 60 * 1000; // timeout in millis
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_TIMEOUT)
.setConnectTimeout(CONNECTION_TIMEOUT)
.setSocketTimeout(CONNECTION_TIMEOUT)
.build();
CloseableHttpClient httpClient = getClient();
String payload ="{\"craccountno\":\"1006973695\",\"transactionType\":\"Internal\",\"amount\":\"11.00\",\"charges\":\"0\",\"draccountno\":\"1000203150\",\"transref\":\"MOJ54CVCCD467\",\"narration\":\"Transfer to ONWUASANYA CHIDILE OBINNA\",\"craccountname\":\"MOJEC PLC\",\"source\":\"MOJEC_MIDDLEWARE\",\"draccountname\":\"OBINNA CHIDILE ONWUASANYA\"}";
System.out.println("Time out for webservice is configured");
System.out.println("outgoing request: " + payload);
// HttpEntity httpEntity = new ByteArrayEntity(payload.getBytes("UTF-8"));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(payload.getBytes("UTF-8")));
entity.setContentLength(payload.getBytes("UTF-8").length);
String url = "http://localhost:8080/T24Gateway/services/qucoon/transaction/ft";
System.out.println("URL for Payment is " + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setHeader("nonce", nonce);
httpPost.setHeader("Timestamp", timestamp);
httpPost.setHeader("Authorization", authorization);
httpPost.setHeader("Signature", signature);
httpPost.setHeader("Content-Type","application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
String encodedData = URLEncoder.encode( payload.toString(), "UTF-8");
//httpPost.(Integer.toString(encodedData.length()) );
httpPost.setHeader("User-Agent", "Pigeon");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
String rawResponse = EntityUtils.toString(response.getEntity());
System.out.println("Raw response :" + rawResponse);
resp = new JSONObject(rawResponse);
}
catch(ConnectTimeoutException ex)
{
System.out.println("Timeout connecting to T24 service" + ex.getMessage());
}
catch(SocketTimeoutException ex)
{
System.out.println("Timeout receiving response from t24 service" + ex.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return resp;
}
用于上述目的的客户配置
public static CloseableHttpClient getClient() throws Exception
{
CloseableHttpClient client = HttpClients.custom().setUserAgent( "Pigeon")
.setSSLSocketFactory(new SSLConnectionSocketFactory(
SSLContexts.createSystemDefault(),
new String[]{"TLSv1.2"},
new String[] {"TLS_RSA_WITH_AES_256_CBC_SHA256"},
SSLConnectionSocketFactory.getDefaultHostnameVerifier()))
.build();
return client;
}
工作代码
public static void postJson(String strUrl,String jsonString) throws UnsupportedEncodingException, ProtocolException, IOException, Exception
{
final StringBuilder builder = new StringBuilder(2048);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat sf = new SimpleDateFormat("MM-dd-yyyy");
String dt=sdf.format(date);
Date dtt = null;
try {
dtt = sf.parse(dt);
} catch (ParseException ex) {
//Logger.getLogger(PostMaster.class.getName()).log(Level.SEVERE, null, ex);
ex.getStackTrace();
}
System.out.println(dtt.toString().substring(0,10).replace(' ', '_'));
DateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
String SignatureMethod="SHA512";
String authorization1=null;
Date today = Calendar.getInstance().getTime();
String created = dateFormatter.format(today);
String Timestamp=created;
String nonce="342353523355241";
String username="QUCOONAPIUSER";
String password="bASMFLp7D9uEDb";
String authorization=username+":"+password;
String UserSecretKey="T888MdaepNXyNpE5RMsE32VRcDsKrYmX";
try {
authorization1="Basic "+ DatatypeConverter.printBase64Binary(authorization.getBytes("UTF-8"));
System.out.println("authorization1: "+authorization1);
} catch (UnsupportedEncodingException ex) {
//Logger.getLogger(T24InterfaceClients.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
String concat= nonce+":"+ created+":"+username+":"+UserSecretKey;
System.out.println("concat: "+concat);
String Signature = hash(concat, SignatureMethod);
System.out.println("Signature: "+Signature);
URI uri =null;
try {
uri = new URI(strUrl);
} catch (URISyntaxException ex) {
//Logger.getLogger(T24InterfaceClients.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
JSONObject JsonObj = new JSONObject(jsonString);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) uri.toURL().openConnection();
} catch (IOException ex) {
//Logger.getLogger(T24InterfaceClients.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
String encodedData = URLEncoder.encode( JsonObj.toString(), "UTF-8");
conn.setRequestProperty( "Content-Length", Integer.toString(encodedData.length()) );
conn.setRequestProperty("User-Agent", "Pigeon");
conn.setRequestProperty("Authorization", authorization1);
conn.setRequestProperty("Timestamp", Timestamp);
conn.setRequestProperty("Nonce", nonce);
conn.setRequestProperty("Signature", Signature);
conn.setRequestProperty("SignatureMethod", SignatureMethod);
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(JsonObj.toString().getBytes());
out.flush();
//Thread.sleep(2000);
int code = conn.getResponseCode();
String message = conn.getResponseMessage();
InputStream inputStream = conn.getInputStream();
int chr;
while ((chr = inputStream.read()) != -1)
{
builder.append((char) chr);
}
// convert response to JSON array
final JSONArray jsa = new JSONArray(builder.toString().replace("{", "[{").replace("}", "}]"));
// extract out data of interestW
if(jsa.length()==0)
{
throw new Exception("Failure to send payment advice");
}
for (int i = 0; i < jsa.length(); i++)
{
final JSONObject jo = (JSONObject) jsa.get(i);
System.out.println(jo.toString());
}
// System.out.println(Signature);
}