I'm trying to integrate payu poland payment system to my website but cant get success response. Website done by jsp. Here is link that payu gave for help click im using "create a new order" for configuration. But its not retrieving any answer. Could anywane help me? Here is my jsp code:
`public static String sendPostRequest2(String requestUrl, String payload, String x, String y) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
writer.write(payload);
}
connection.setRequestProperty(x, y);
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
connection.disconnect();
} catch (IOException e) {
try {
URL url = new URL(requestUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
jsonString.append(new RuntimeException(e.getMessage()));
} catch (MalformedURLException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
}
}
return jsonString.toString();
}
public static String get() {
String x = "";
String payload2 = "{ 'notifyUrl': 'https://your.eshop.com/notify', 'customerIp': '127.0.0.1', 'merchantPosId': '145227', 'description': 'RTV market', 'currencyCode': 'PLN', 'totalAmount': '21000', 'products': [ { 'name': 'Wireless mouse', 'unitPrice': '15000', 'quantity': '1' }, { 'name': 'HDMI cable', 'unitPrice': '6000', 'quantity': '1' } ]}";
String requestUrl2 = "https://secure.payu.com/api/v2_1/orders/";
x += sendPostRequest2(requestUrl2, payload2, "Authorization", "Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd");
return x;
}`
set the redirect turn off after that you will get the json response. So in your java code set redirect false.
connection.setInstanceFollowRedirects(false);
Related
I'm try to post request with HttpURLConnection
This is request body:
This is request header:
This is my Code:
public static String postSms(long mNo,long cepNo, String mesaj){
String responseLine = null;
String url = getSmsUrl();
String authKey = getSmsAuthKey();
try {
URL s_url = new URL(url);
httpCon = (HttpURLConnection) s_url.openConnection();
if(authKey != null){
httpCon.setRequestProperty("yd-x-token", authKey);
}
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "application/json; utf-8");
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setDoOutput(true);
int responseCode = httpCon.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
JSONObject msj = new JSONObject();
msj.put("toNumber", cepNo);
msj.put("smsText", mesaj);
try(OutputStream os = httpCon.getOutputStream()) {
byte[] input = msj.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(httpCon.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}
}else return "ER|[sendNotification][Sms] <===> "+responseCode;
} catch (MalformedURLException e) {
log.error("ER|[sendNotification][Sms] <===> Hata "+e);
return "ER|[sendNotification][Sms] <===> Hata "+e;
} catch (IOException e) {
log.error("ER|[sendNotification][Sms] <===> Hata "+e);
return "ER|[sendNotification][Sms] <===> Hata "+e;
}catch (JSONException e){
}
return "OK";
}
When i try postman like two photos, it's happens successs. But when i try with HttpURLConnection, response code = 500 . Sometimes responseCode was coming 401 but when they give new token that changes with httpstatus 500. Why I'm getting this error.
If you get a status 401, it means you don't have permission for access this URL. This is why they gave you a new token, you got a status 500. So make sure that you always have right token before calling that request.
For the status 500, It is an issue of server side. Tell your server developer, check it.
By the way, It is stupid url with ".json" at the end.
True way is :
public static String postSms(long mNo,long cepNo, String mesaj){
String responseLine = null;
String url = getSmsUrl();
String authKey = getSmsAuthKey();
try {
URL s_url = new URL(url);
httpCon = (HttpURLConnection) s_url.openConnection();
if(authKey != null){
httpCon.setRequestProperty("yd-x-token", authKey);
}
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "application/json; utf-8");
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setDoOutput(true);
JSONObject msj = new JSONObject();
msj.put("toNumber", cepNo);
msj.put("smsText", mesaj);
try(OutputStream os = httpCon.getOutputStream()) {
byte[] input = msj.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = httpCon.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
try(BufferedReader br = new BufferedReader(
new InputStreamReader(httpCon.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}
}else return "ER|[sendNotification][Sms] <===> "+responseCode;
} catch (MalformedURLException e) {
log.error("ER|[sendNotification][Sms] <===> Hata "+e);
return "ER|[sendNotification][Sms] <===> Hata "+e;
} catch (IOException e) {
log.error("ER|[sendNotification][Sms] <===> Hata "+e);
return "ER|[sendNotification][Sms] <===> Hata "+e;
}catch (JSONException e){
}
return "OK";
}
I want to invoke remote server using HttpURLConnection, here is my function:
public String invokeAwvsServer(String api, String param, String method){
System.out.println(api+param);
BufferedReader reader = null;
HttpURLConnection connection = null;
OutputStreamWriter out = null;
try {
URL url = new URL(api);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth", apiKey);
connection.connect();
if(method.equalsIgnoreCase("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuffer res = new StringBuffer();
while ((line = reader.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
I use this function in its own class and works well, but if I call it in other class ,the remote server return 500 status code and JVM throws exception like:
java.io.IOException: Server returned HTTP response code: 500 for URL:...
What`s the reason?Thanks a lot:)
So I'm trying to connect to our database via Xserve, AT the moment I'm trying to access the token for the user. I'm using the correct username and password along with the context type and grant type; I know this because I've tried the same POST method via googles postmaster extension. For whatever reason when I try the same thing on Android, at least what I think is the same, it gives me a 400 response code and doesn't return anything.
Here's the code used to connect:
private HttpURLConnection urlConnection;
#Override
protected Boolean doInBackground(Void... params) {
Boolean blnResult = false;
StringBuilder result = new StringBuilder();
JSONObject passing = new JSONObject();
try {
URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");
// set up connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// set up parameters to pass
passing.put("username", mEmail);
passing.put("password", mPassword);
passing.put("grant_type", "password");
// add parameters to connection
OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(passing.toString());
// If request was good
if (urlConnection.getResponseCode() == 200) {
blnResult = true;
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
}
//JSONObject json = new JSONObject(builder.toString());
Log.v("Response Code", String.format("%d", urlConnection.getResponseCode()));
Log.v("Returned String", result.toString());
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return blnResult;
}
I haven't stored the result into the JSONObject yet as I'll use that later, but I expected some kind of output via the "Log.v".
Is there anything that stands out?
try {
URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");
parameters = new HashMap<>();
parameters.put("username", mEmail);
parameters.put("password", mPassword);
parameters.put("grant_type", "password");
set = parameters.entrySet();
i = set.iterator();
postData = new StringBuilder();
for (Map.Entry<String, String> param : parameters.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
postDataBytes = postData.toString().getBytes("UTF-8");
// set up connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.getOutputStream().write(postDataBytes);
// If request was good
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
}
Log.v("Login Response Code", String.valueOf(urlConnection.getResponseCode()));
Log.v("Login Response Message", String.valueOf(urlConnection.getResponseMessage()));
Log.v("Login Returned String", result.toString());
jsonObject = new JSONObject(result.toString());
token = jsonObject.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
if (token != null) {
jsonObject = driverInfo(token);
}
}
this works, although I've moved it to it's own function now.
changed the input type to a HashMap
I am facing a problem while using POST Method in Java nowadays. I am receiving
Exception in thread "main" java.lang.RuntimeException: Server returned HTTP response code: 411 for URL.
I couldn't find any available document anywhere. None of them were useful. How do I fix it?
My code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class req {
public static void main(String[] args) {
sendPostRequest(requestURL);
}
private static String sendPostRequest(String requestUrl) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
byte[] data = requestUrl.getBytes("UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
connection.setRequestProperty("Authorization", "Basic " + "usename:password");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
}
Perfectly working method:
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
If you are returning a JSON in your response:
public JSONObject getPostResult(String json){
if(!json.isEmpty()) {
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON_ERROR", "Error parsing data " + e.toString());
}
}
return jObj;
}
If you are still having trouble, maybe this will help. I did not test, machine does not have java installed.
You should also set all other headers that you need.
public static String PostRequest(String requestUrl, String username, String password) {
StringBuilder jsonString = new StringBuilder();
HttpURLConnection connection = null;
try {
URL url = new URL(requestUrl);
connection = (HttpURLConnection)url.openConnection();
byte[] authData = Base64.encode((username + password).getBytes());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + new String(authData));
connection.setRequestProperty("Content-Length", String.valueOf(authData.length));
try (DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
writer.writeBytes("REPLACE ME WITH DATA TO BE WRITTEN");
writer.flush();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String data = null;
while ((data = reader.readLine()) != null) {
jsonString.append(data);
}
}
} catch (IOException ex) {
//Handle exception.
} finally {
if (connection != null)
connection.disconnect();
}
return jsonString.toString();
}
You should send empty data in body if you are using post method.
For example if you are using json data you need to send "{}"
public void Post() throws Exception {
StringBuffer d = new StringBuffer();
String da = "ClearanceDate=2020-08-31&DepositeDate=2020-08-31&BankTransactionNo=UATRYU56789";
URL url = new URL("https://abcd/AddReceipt?" + da);
byte[] postDataBytes = ("https://abcd/AddReceipt?" + da).toString()
.getBytes("UTF-8");
System.out.println("Data--" + postDataBytes);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// con.setRequestProperty("User-Agent",
// "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
con.setRequestProperty(
"Authorization",
"Bearer "
+ "o731WGgp1d913ZOYivnc55yOg0y1Wk7GsT_mnCUKOJf1VChYOdfRjovAxOhyyPKU93ERue6-l9DyG3IP29ObsCNTFr4lGZOcYAaR96ZudKgWif1UuSfVx4AlATiOs9shQsGgb1oXN_w0NRJKvYqD0LLsZLstBAzP1s5PZoaS9c6MmO32AV47FUvxRT6Tflus5DBDHji3N4f1AM0dShbzmjkBCzXmGzEDnU6Jg1Mo5kb884kParngKADG5umtuGbNzChQpMw_A0SyEYaUNh18pXVmnNhqM3Qx5ZINwDEXlYY");
con.setRequestProperty("Accept", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);
int status = con.getResponseCode();
System.out.println("Response status: " + status + "|"
+ con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println("Response status: " + status);
System.out.println(content.toString());
System.out.print("Raw Response->>" + d);
}
I'm trying to connect to Bitcoin wallet from Java. But i get network exception: Server redirected too many times. I would be very glad if someone helps me understand.
Here's my code:
public static void SetupRPC() {
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("admin", "admin".toCharArray());
}
});
URL serverURL = null;
try {
serverURL = new URL("http://127.0.0.1:44843");
} catch (MalformedURLException e) {
System.err.println(e.getMessage());
}
JSONRPC2Session mySession = new JSONRPC2Session(serverURL);
String method = "getinfo";
int requestID = 0;
JSONRPC2Request request = new JSONRPC2Request(method, requestID);
// Send request
JSONRPC2Response response = null;
try {
response = mySession.send(request);
} catch (JSONRPC2SessionException e) {
System.err.println(e.getMessage());
}
if (response.indicatesSuccess())
System.out.println(response.getResult());
else
System.out.println(response.getError().getMessage());
}
And .conf file:
rpcuser="admin"
rpcpassword="admin"
rpcallowip=*
rpcport=44843
server=1
daemon=1
listen=1
rpcconnect=127.0.0.1
If these are your code and .conf, then remove the " in your conf file. Or add \" to your string.
So this
return new PasswordAuthentication ("\"admin\"", "\"admin\"".toCharArray());
or this
rpcuser="admin"
rpcpassword="admin"
Also you cannot have # in your password or username(which was my case).
After I found this I got an Invalid JSON-RPC 2.0 response.
My solution was to change !jsonObject.containsKey("error") to (!jsonObject.containsKey("error") || jsonObject.get("error") == null) in the function
public JSONRPC2Response parseJSONRPC2Response(final String jsonString) which is located in the base of JSONRPC 2.0 in JSONRPC2Parser.java somewhere around line 495.
EDIT: This was on the DogeCoin-QT, so maybe the Bitcoin-QT does not have this problem.
Ok, i solve this problem:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pass".toCharArray());
}
});
String uri = "http://127.0.0.1:8332";
String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"getbalance\"}";
String contentType = "application/json";
HttpURLConnection connection = null;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length));
connection.setUseCaches(true);
connection.setDoInput(true);
OutputStream out = connection.getOutputStream();
out.write(requestBody.getBytes());
out.flush();
out.close();
} catch (IOException ioE) {
connection.disconnect();
ioE.printStackTrace();
}
try {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response);
} else {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}