i am currently trying to use REST api provided by Paypal to create my own service using servlet. I manage to transfer the cURL code into HttpsURLConnection using java.
Here is my code:
JSONObject returnJson = new JSONObject();
PrintWriter out = response.getWriter();
JSONParser jparser = new JSONParser();
try{
String inputStr = request.getParameter("input");
System.out.println(inputStr);
JSONObject inputJson = (JSONObject) jparser.parse(inputStr);
String accessToken = (String) inputJson.get("access_token");
String invoiceId = (String) inputJson.get("invoiceId");
String url = "https://api.sandbox.paypal.com/v1/invoicing/invoices/"+invoiceId;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("PUT");
con.setRequestProperty("Accept-Language", "text/html; charset=UTF-8");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer "+accessToken);
//Tentatively, the input is hard coded, after integration, the input comes from http request.
//However, only merchant email in mandatory for invoice creation in sand box so far
//For details of invoice attributes please refer to this link--> https://developer.paypal.com/docs/api/#update-an-invoice
String urlJsonString = "{\"id\":\""+invoiceId+"\",\"status\":\"DRAFT\",\"merchant_info\":{\"email\":\"rui.song.2013-facilitator#sis.smu.edu.sg\",\"first_name\":\"Dennis\",\"last_name\":\"Doctor\",\"business_name\":\"MedicalProfessionals,LLC\",\"phone\":{\"country_code\":\"US\",\"national_number\":\"5032141716\"},\"address\":{\"line1\":\"1234MainSt.\",\"city\":\"Portland\",\"state\":\"LALA\",\"postal_code\":\"97217\",\"country_code\":\"US\"}},\"billing_info\":[{\"email\":\"sally-patient#example.com\"}],\"shipping_info\":{\"first_name\":\"Sally\",\"last_name\":\"Patient\",\"business_name\":\"Notapplicable\",\"address\":{\"line1\":\"1234BroadSt.\",\"city\":\"Portland\",\"state\":\"LALA\",\"postal_code\":\"97216\",\"country_code\":\"US\"}},\"items\":[{\"name\":\"Sutures\",\"quantity\":100,\"unit_price\":{\"currency\":\"USD\",\"value\":\"250\"}}],\"invoice_date\":\"2014-01-07PST\",\"payment_term\":{\"term_type\":\"NO_DUE_DATE\"},\"tax_calculated_after_discount\":false,\"tax_inclusive\":false,\"note\":\"MedicalInvoice16Jul,2013PST\",\"total_amount\":{\"currency\":\"USD\",\"value\":\"250\"}}";
System.out.println(urlJsonString);
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlJsonString);
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
out.print(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer res= new StringBuffer();
while ((inputLine = in.readLine()) != null) {
res.append(inputLine);
}
in.close();
returnJson = (JSONObject) jparser.parse(res.toString());
System.out.println(returnJson);
}catch(Exception e){
e.printStackTrace();
returnJson.put("message", e);
}
out.print(returnJson);
I am testing the service on localhost, and i will manually pass in TWO parameters: "access_token" and "invoiceId" like this:
http://localhost:8080/Authentication/PaypalUpdateInvoiceServlet?input={"access_token":"A015Rv3XNo4fmFh4JC2sJiGjl1oEQ5w-B9azU.H6nlzMm1s","invoiceId":"INV2-9TRP-2S2R-OPBD-XK9T"}
These two pieces of info are obtained by me using the similar code i mentioned above.
I only modified codes in the entier HttpsURLConnection part to correspond with the cURL request and response sample provided in Paypal site. Link -->(https://developer.paypal.com/docs/api/#update-an-invoice)
Thus far, i successfully implement Create, Retrieve for invoice. I use the same way to make the servlet call with the specific parameters required and are able to get the expected response show on Paypal site.
BUT Now i am stuck with update invoice. When i make the servlet call.
i will receive:
500{"message":java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.sandbox.paypal.com/v1/invoicing/invoices/IINV2-9TRP-2S2R-OPBD-XK9T}
Can anyone help me explain why i get this error and how shall i fix this?
Related
I have write this code for send notification using fcm by java server code. But it is throwing exception Server returned HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send
public static void pushFCMNotification(String userDeviceIdKey) throws Exception{
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "Notificatoin Title"); // Notification title
info.put("body", "Hello Test notification"); // Notification body
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + json);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
/*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();*/
}
According to the oficial documentation:
Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.
source: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
However, make sure that the JSON request is properly formatted. Try to update your question with the json.toString() and check that your API key is still valid using the procedure described in: Checking the validity of a server key
I need to send a post request to url which is formed as follows:
www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45
Using HttpPost client in java, how can post request to such query strings
I could connect from javascript easily through ajax but from java client, it's failing.
(I know sending querystring in post request is stupid idea. Since I am connecting to someone else's server I cannot not change the way it is)
Here is one way to send JSON in a POST request using Java (without Apache libraries). You might find this helpful:
//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";
//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}
I'm sending data to an API from Java using POST.
What I'm trying to do is send a particular variable to the API in the POST request, and then use the value of it. But currently the value is empty. The API is definitely being called.
My Java looks like this:
String line;
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL("https://www.x.com/api.php");
String payload = "{\"variable1\":\"value1\",\"variable2\":\"value2\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
This is based on: How to send Request payload to REST API in java?
Currently the value isn't being read correctly. Am I sending it correctly in Java? Do I have to do something to decode it?
The $_POST variable is not set for all HTTP POST requests, but only for specific types, e.g application/x-www-form-urlencoded.
Since you are posting a request containing JSON entity (application/json), you need to access it as follows.
$json = file_get_contents('php://input');
$entity= json_decode($json, TRUE);
You can try to use the following code instead of your String variable payload:
List<NameValuePair> payload = new ArrayList<NameValuePair>();
payload.add(new BasicNameValuePair("variable1", "value1");
That worked for me
I have an application (Java) that needs to send json to a php web service.
This is my method to send User in JSON :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
And my php code :
$string=$_POST['json'];
I tried to insert in my database but $_POST['json'] does not exist.
I didn't see you to posting anything. Add this to your code:
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
This is not right:
con.setRequestProperty("json", json);
setRequestProperty is not used to set the HTTP payload. It is used to set the HTTP headers. For example, you should set the content type accordingly anyway. Like this:
con.setContentType("application/json");
The actual data that you are going to post goes into the HTTP body. You just write it to the end of the stream (before flush):
Here it depends on your implementation on the web server if the data needs to be escaped. If you read the body of the post and interpret it as JSON straight away, it does not need to be escaped:
wr.write(json);
If you transmit one or more JSON strings through parameters (which it looks like, since you are parsing it on the server like $_POST['json']), then you need to url-escape the string:
wr.write("json=" + URLEncoder.encode(json, "UTF-8"));
Im not very familiar with php. You might need to url-decode the string on the server before processing the received json-string any further.
Thx for your help.
This works :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
OutputStream os = con.getOutputStream();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.write(new String("json=" + json).getBytes());
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
PHP :
$string=$_POST['json'];
I'm overhauling certain parts of my app to use the new GCM service to replace C2DM. I simply want to create the JSON request from a Java program for testing and then read the response. As of right now I can't find ANY formatting issues with my JSON request and the google server always return code 400, which indicates a problem with my JSON.
http://developer.android.com/guide/google/gcm/gcm.html#server
JSONObject obj = new JSONObject();
obj.put("collapse_key", "collapse key");
JSONObject data = new JSONObject();
data.put("info1", "info_1");
data.put("info2", "info 2");
data.put("info3", "info_3");
obj.put("data", data);
JSONArray ids = new JSONArray();
ids.add(REG_ID);
obj.put("registration_ids", ids);
System.out.println(obj.toJSONString());
I print my request to the eclipse console to check it's formatting
byte[] postData = obj.toJSONString().getBytes();
try{
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpsURLConnection.setDefaultHostnameVerifier(new JServerHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + API_KEY);
System.out.println(conn.toString());
OutputStream out = conn.getOutputStream();
// exception thrown right here. no InputStream to get
InputStream in = conn.getInputStream();
byte[] response = null;
out.write(postData);
out.close();
in.read(response);
JSONParser parser = new JSONParser();
String temp = new String(response);
JSONObject temp1 = (JSONObject) parser.parse(temp);
System.out.println(temp1.toJSONString());
int responseCode = conn.getResponseCode();
System.out.println(responseCode + "");
} catch(Exception e){
System.out.println("Exception thrown\n"+ e.getMessage());
}
}
I'm sure my API key is correct as that would result in error 401, so says the google documentation. This is my first time doing JSON but it's easy to understand because of its simplicity. Anyone have any ideas on why I always receive code 400?
update: I've tested the google server example classes provided with gcm so the problem MUST be with my code.
{"collapse_key":"new-test-notification","data":{"info1":"info_1","info3":"info_3","info2":"info 2"},"registration_ids":["APA91bG3bmCSltzQYl_yOcjG0LPcR1Qemwg7osYJxImpSuWZftmmIjUGH_CSDG3mswKuV3AAb8GSX7HChOKGAYHz1A_spJus5mXFtfOrK0fouBD7QBpKnfc_ly0t3S8vSYWRjuGxtXrt"]}
I solved it using a different approach so it must have been my original implementation.
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("username",username));
list.add(new BasicNameValuePair("deviceId",regId));
list.add(new BasicNameValuePair("deviceType","AndroidPhone"));
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("example.url.com");
post.setEntity(new UrlEncodedFormEntity(list));
ResponseHandler<String> handler = new BasicResponseHandler();
HttpResponse response = client.execute(post);
String responseString = handler.handleResponse(response);
JSONObject jsonResponse = new JSONObject(responseString);
I'm reading here that you should use your 'Key for browser apps'
GCM with PHP (Google Cloud Messaging) (in comments)
Try to reproduce the error using curl or another command-line tool so we can eliminate the possibility that there's a bug in your java that we're all missing.