PUT request on Volley Android - android-studio

I need to send a PUT Request to a server. The body requires a key which is a String and a value which has to be a JSONObject, with content type being x-www-form-urlencoded. I've attached the required PUT request of Postman, the code I'm using and the error I'm getting below. Please help!
private void modifyObject(String object, String objectId) throws JSONException {
/**PUT REQUEST*/
String putUrl = api.url;
Log.d("putUrl", putUrl);
JSONObject jsonObject = new JSONObject();
jsonObject.put(dateName, actualDate);
jsonObject.put(locationName,actualLocation);
jsonObject.put(status,actualStatus);
final String requestBody = "data=" + jsonObject;
Log.d("requestBody", requestBody);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, putUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", String.valueOf(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-type", "application/json");
headers.put("Authorization", accessToken);
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
mRequestQueue.add(request);
}
W/System.err: com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
W/System.err: at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:90)
W/System.err: at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:143)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)
W/System.err: Caused by: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:163)
at org.json.JSONObject.<init>(JSONObject.java:176)
W/System.err: at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:85)

write this
final String requestBody = jsonObject.toString();
instead of this
final String requestBody = "data=" + jsonObject;

Related

Problem with integrate Strip in Android Studio

java.lang.NullPointerException: Parameter specified as non-null is
null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter,
parameter id
at com.stripe.android.paymentsheet.PaymentSheet$CustomerConfiguration.(PaymentSheet.kt)
at com.abdullahalzazai.welcome2.MainActivity2.paymentFlow(MainActivity2.java:102)
at com.abdullahalzazai.welcome2.MainActivity2.access$000(MainActivity2.java:29)
at com.abdullahalzazai.welcome2.MainActivity2$1.onClick(MainActivity2.java:57)
at android.view.View.performClick(View.java:5637)
public class MainActivity2 extends AppCompatActivity {
Button payment;
String PublishableKey ="pk_test_51MWOxeHw41kgZTMnEfStv1DZsXRvXAQk3RrZrv7tH3U8KHzGhvpNJsyrri7SQpY9nOvyeLIbTfTVa1tK7nh5egfu00A0dBYpw9";
String SecretKey="sk_test_51MWOxeHw41kgZTMnhE1cH6j3eo9SaiSCz1bO2JdI5A0T3392jHFHMhexotB8MslRlHwOGoEDqtsKnY5opU3kLTxB00XBmE2Dox";
String CustomerId;
String EphericalKey;
String ClientSecret;
PaymentSheet paymentSheet;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
payment= findViewById(R.id.payment);
PaymentConfiguration.init(this,PublishableKey);
paymentSheet = new PaymentSheet(this,paymentSheetResult -> {
onPaymentresult(paymentSheetResult);
});
payment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paymentFlow();
}
});
StringRequest request = new StringRequest(Request.Method.POST, "https://api.stripe.com/v1/customers ",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
CustomerId = object.getString("id");
Toast.makeText(MainActivity2.this,CustomerId,Toast.LENGTH_SHORT).show();
getEmphericalKey();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization","Bearer"+SecretKey);
return header;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void paymentFlow() {
paymentSheet.presentWithPaymentIntent(ClientSecret,new PaymentSheet.Configuration("Learn with Arvind",new PaymentSheet.CustomerConfiguration(
CustomerId,
EphericalKey
)));
}
private void onPaymentresult(PaymentSheetResult paymentSheetResult) {
if (paymentSheetResult instanceof PaymentSheetResult.Completed){
Toast.makeText(this,"payment success",Toast.LENGTH_SHORT).show();
}
}
private void getEmphericalKey() {
StringRequest request = new StringRequest(Request.Method.POST, "https://api.stripe.com/v1/ephemeral_keys",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
EphericalKey = object.getString("id");
Toast.makeText(MainActivity2.this,CustomerId,Toast.LENGTH_SHORT).show();
getClintSecret(CustomerId,EphericalKey);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization","Bearer"+SecretKey);
header.put("Stripe-Version","2022-08-01");
return header;
}
#Nullable
#Override
protected Map<String, String> getPostParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("customer",CustomerId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void getClintSecret(String customerId, String ephericalKey) {
StringRequest request = new StringRequest(Request.Method.POST, " https://api.stripe.com/v1/payment_intents",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
ClientSecret=object.getString("client_secret");
Toast.makeText(MainActivity2.this,ClientSecret,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
header.put("Authorization","Bearer"+SecretKey);
return header;
}
#Nullable
#Override
protected Map<String, String> getPostParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("customer",CustomerId);
params.put("amount","100"+"00");
params.put("currency_payment_methods[enabled]","true");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}`

readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is STRING Error?

My code is like below, what should I do to avoid this error?
#RequestMapping(method = RequestMethod.POST, path = "/deneme", consumes = "application/json")
public void logout(#RequestBody Map<String, Object> userId) {
tokensService.logout(userId.get("userId").toString());
}
public void logout(String userId){
try {
tokensRepository.logout(userId,"");
}
catch (Exception e) {
System.out.println(e.getMessage());
}`public interface TokensRepository extends MongoRepository<Tokens, String> {
#Query("Update tokens t set t.token=:token where t._id=:userId")
void logout(#Param("userId") String userId, #Param("token") String token);
}`

Why my variables are set to null after i volley call is succeed

I do not why my private variable values are getting to null after the Volley request
When i am printing the values in onResponse, i am getting required values, but after volley request is completed, I am getting null.
ListView userListView;
StringRequest stringRequest=null;
ProgressDialog progressDialog;
private String[] strUsername;
private String[] strUserItems;
private String[] strUserImagePaths;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_listing);
userListView=findViewById(R.id.userListView);
progressDialog=new ProgressDialog(this);
StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
displayUserListing();
UserListCustomViewAdapter viewAdapter=new UserListCustomViewAdapter(this,strUsername,strUserImagePaths,strUserItems);
userListView.setAdapter(viewAdapter);
}
private void displayUserListing()
{
progressDialog.setMessage("Getting User List...");
progressDialog.show();
stringRequest=new StringRequest(
Request.Method.GET, Constants.URL_GetUserList, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
progressDialog.dismiss();
try {
Log.d("first","before");
JSONArray jsonObj=new JSONArray(response);
strUsername=new String[jsonObj.length()];
strUserItems=new String[jsonObj.length()];
strUserImagePaths=new String[jsonObj.length()];
String str=null;
for(int i=0;i<jsonObj.length();i++)
{
JSONObject jsonObject=jsonObj.getJSONObject(i);
strUsername[i]=jsonObject.getString("user_name");
strUserItems[i]=jsonObject.getString("user_item");
strUserImagePaths[i]=jsonObject.getString("user_image_path");
str+=strUsername[i];
}
Log.d("first","after"+str);
}catch (Exception e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
Log.d("myerror","I got some error");
NetworkResponse networkResponse = error.networkResponse;
Log.d("myerror1",error.getMessage());
// Toast.makeText(getApplicationContext(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String,String> params=new HashMap<String,String>();
params.put("struserid","1");
//params.put("serviceid","1");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
I think you are using your variables before initializing it. Call the adapter after you parsing value.

RestTemplate postForObject response getting truncated

Trying to fetch the response using spring web client, but the result response is getting truncated as the response size is more than that of string class. Is there any other way to get the response without being truncated?
LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
//String response = "";
try{
File tempFile = File.createTempFile("ccda", "File");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(ccdaFile.getInputStream(), out);
requestMap.add("ccdaFile", new FileSystemResource(tempFile));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<LinkedMultiValueMap<String, Object>>(requestMap, headers);
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
String response = restTemplate.postForObject("localhost:8080",
requestEntity, String.class);
tempFile.delete();
}catch(Exception exc)
{
exc.printStackTrace();
}
You may use an InputStream
I think you may do in this way:
InputStream is = rt.execute("localhost:8080", HttpMethod.POST, requestCallback, responseExtractor);
Where requestCallback is an implementation of org.springframework.web.client.RequestCallback like this one
public class MyRequestCallback implements RequestCallback
{
#Override
public void doWithRequest(ClientHttpRequest request) throws IOException
{
request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON_VALUE);
request.getHeaders().add(HttpHeaders.ACCEPT, MimeTypeUtils.APPLICATION_JSON_VALUE);
}
}
While responseExtractor may by an instance of this class
public class MyResponseExtractor implements ResponseExtractor<InputStream>
{
#Override
public Boolean extractData(ClientHttpResponse response) throws IOException
{
HttpStatus status = response.getStatusCode();
switch (status)
{
case OK:
return response.getBody();
default:
return null;
}
}
}
Once obtained the InputStream you can manage it
Hope it is usefull

Download file, filename doesn't work in portlet

I set filename in the HttpServletResponse header but when I download it has not this filename
FileInputStream fis = new FileInputStream(fileDocumento);
PortletResponse portletResponse=(PortletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
HttpServletResponse res = PortalUtil.getHttpServletResponse(portletResponse);
res.setHeader("Content-Disposition", "attachment; filename=schedaObiettivoTAC_.docx");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
res.flushBuffer();
OutputStream out=res.getOutputStream();
out.write(IOUtils.toByteArray(fis));
out.close();
fis.close();
You should not use the HttpServletResponse. Instead you should create a custom Resource and ResourceHandler:
CustomResourceHandler.java:
public final class CustomResourceHandler extends ResourceHandlerWrapper {
// Public Constants
public static final String LIBRARY_NAME = "exampleLib";
public static final String RESOURCE_NAME = "exampleName";
// Private Data Members
private ResourceHandler wrappedResourceHandler;
public CustomResourceHandler(ResourceHandler resourceHandler) {
this.wrappedResourceHandler = resourceHandler;
}
#Override
public Resource createResource(String resourceName, String libraryName) {
if (LIBRARY_NAME.equals(libraryName)) {
if (RESOURCE_NAME.equals(resourceName)) {
return new CustomResource(libraryName, resourceName,
"exampleFileName.txt", "Example Content");
}
else {
return super.createResource(resourceName, libraryName);
}
}
else {
return super.createResource(resourceName, libraryName);
}
}
#Override
public ResourceHandler getWrapped() {
return wrappedResourceHandler;
}
#Override
public boolean libraryExists(String libraryName) {
if (LIBRARY_NAME.equals(libraryName)) {
return true;
}
else {
return super.libraryExists(libraryName);
}
}
/* package-private */ static final class CustomResource extends Resource {
private final String content;
private final Map<String, String> responseHeaders;
private final String requestPath;
private final URL url;
public CustomResource(String libraryName, String resourceName,
String fileName, String content) {
super.setLibraryName(libraryName);
super.setResourceName(resourceName);
super.setContentType("text/plain");
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put("Content-Disposition",
"attachment; filename=" + fileName + ";");
this.responseHeaders = Collections.unmodifiableMap(responseHeaders);
StringBuilder sb = new StringBuilder();
sb.append(ResourceHandler.RESOURCE_IDENTIFIER);
sb.append("/");
sb.append(super.getResourceName());
sb.append("?ln=");
sb.append(super.getLibraryName());
this.requestPath = sb.toString();
URL url;
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
url = new URL(externalContext.encodeResourceURL(this.requestPath));
}
catch (MalformedURLException e) {
url = null;
}
this.url = url;
this.content = content;
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(
content.getBytes(StandardCharsets.UTF_8));
}
#Override
public String getRequestPath() {
return requestPath;
}
#Override
public Map<String, String> getResponseHeaders() {
return responseHeaders;
}
#Override
public URL getURL() {
return url;
}
#Override
public boolean userAgentNeedsUpdate(FacesContext facesContext) {
// Return false if the content cannot change dynamically.
return true;
}
}
}
WEB-INF/faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<!-- ... -->
<resource-handler>custom.resource.handler.CustomResourceHandler</resource-handler>
</application>
<!-- ... -->
</faces-config>
Here's some example code for downloading the resource:
<h:outputLink target="_blank" value="#{bean.getDownloadURL(facesContext)}">
<h:outputText value="download" />
</h:outputLink>
public String getDownloadURL(FacesContext facesContext) {
return facesContext.getApplication().getResourceHandler()
.createResource(CustomResourceHandler.RESOURCE_NAME,
CustomResourceHandler.LIBRARY_NAME)
.getURL().toString();
}
You can also look at the Liferay Faces JSF Export PDF for a full portlet example to download/export a file.
If you are in the action or render phase of your portlet (what I would guess for a JSF portlet): there is a ResponseWrapper which will suppress any header. I'm using this method to find the response for sending binary data during the JSF lifecycle:
public static HttpServletResponse getHttpServletResponse() {
final FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
throw new IllegalStateException("Not inside a JSF request");
}
final Object responseObject = facesContext.getExternalContext().getResponse();
if (responseObject instanceof HttpServletResponse) {
return (HttpServletResponse) responseObject;
}
if (responseObject instanceof PortletResponse) {
// Use Liferays util to find the real response
HttpServletResponse response = PortalUtil.getHttpServletResponse((PortletResponse) responseObject);
// Find the outer most response (setting the headers would have no effect, as we are included)
while (response instanceof ServletResponseWrapper) {
final ServletResponse servletResponse = ((ServletResponseWrapper) response).getResponse();
if (!(servletResponse instanceof HttpServletResponse)) {
break;
}
response = (HttpServletResponse) servletResponse;
}
return response;
}
throw new IllegalStateException("Unknown type of response object: " + responseObject);
}

Resources