HttpsURLConnection 400 Bad Request error occured - java

I need to convert below Swift code to Java.
Swift code works.
But, Java code is not worked.
HttpsURLConnection has failed.
responseCode: 400 (HttpsURLConnection.getResponseCode())
message2: Bad Request (HttpsURLConnection.getResponseMessage())
How can I solve 400 Bad Request error.
In Swift(It worked)
func sendNotification(token: String, message: String) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(firebaseServerKey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"body\":\"\(message)\",\"badge\":\"1\"}}".data(using: .utf8)
}
I wrote in JAVA(not worked)
private void sendNotification(String token, String message) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+firebaseServerKey);
String str = "{\"to\": " + token + ", \"notification\": { \"body\": " + message + ", \"badge\": \"1\"}}";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
int responseCode = conn.getResponseCode(); // responseCode: 400
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.d("Success", String.valueOf(responseCode));
} else {
String code = String.valueOf(responseCode);
String message2 = conn.getResponseMessage(); // message2: Bad Request
Log.d("Fail", String.valueOf(responseCode));
Log.d("Fail2", conn.getResponseMessage());
}
}

Your JSON request body is incorrect. It produce {"to": zxc} which is an invalid json. Change it to
String str = "{\"to\": \"" + token + "\", \"notification\": { \"body\": \"" +
message + "\", \"badge\": \"1\"}}";

Related

Call mail PHP file from Android doesn't work

I have the following function in my Android app:
void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
ParseUser currentUser = ParseUser.getCurrentUser();
StringBuilder messageBuilder = new StringBuilder();
for (int i=0; i<productsOrdered.size(); i++){
messageBuilder.append(productsOrdered.get(i)).append("\n");
}
String mess = messageBuilder.toString();
String parameters = "name=" + currentUser.getString(Configurations.USER_FULLNAME) +
"&fromEmail=" + fromEmail +
"&receiverEmail=" + receiverEmail +
"&messageBody=" + mess +
"&storeName=" + Configurations.MERCHANT_NAME +
"&shippingAddress=" + currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);
String strURL = PHPfileUurl + parameters;
strURL = strURL.replace(" ", "%20");
strURL = strURL.replace("\n", "%20");
Log.i(Configurations.TAG, "PHP STRING URL: " + strURL);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
} else {
InputStream err = conn.getErrorStream();
Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
}
} catch (IOException e) {e.printStackTrace(); }
}
When I call that function the Logcat prints out this message:
I/log-: PHP STRING URL: http://example.com/myapp/email-admin.php?name=Mark%20Doe&fromEmail=myemail#gmail.com&receiverEmail=admin#mydomain.com&messageBody=PRODUCT%20ID:%20Q3nQgZdlFG%20---%20PRODUCT:%20Nike%20Sport%20Shoes%20black%20%20---%20QUANTITY:%201%20---%20SIZE:%20L%20&storeName=Z%20Store%20Inc.&shippingAddress=John%20Doe,%20121%20Church%20Avenue,%20ASD123,%20London,%20UK
I/log-: EMAIL RESPONSE: OK
So I assume everything is fine since the RESPONSE = OK. But it's not, because I will not receive any email at admin#mydomain.com (there is another email address, I've posted a fake one just as an example, the Logcat prints out my real email address as receiverEmail).
Here's my mail.php file:
// POST Variables
$name = $_POST['name'];
$fromEmail = $_POST['fromEmail'];
$receiverEmail = $_POST['receiverEmail'];
$messageBody = $_POST['messageBody'];
$storeName = $_POST['storeName'];
$shippingAddress = $_POST['shippingAddress'];
$headers = 'From: ' .$fromEmail;
// SUBJECT
$subject = "New order from " .$name. " on '" .$storeName. "'";
// COMPOSE MESSAGE
$message =
"ORDER DETAILS:\n".
$messageBody.
"\n\nName: " .$name.
"\nUser Email: " .$fromEmail.
"\nShipping Address: " .$shippingAddress
;
/* Finally send email */
mail($receiverEmail,
$subject,
$message,
$headers
);
/* Result */
echo "Email Sent to: " .$receiverEmail. "\n Message: " .$message;
Does my code have something wrong? is there another way to call a mail.php file from my own server? I've also tried this question, but I cannot import the DefaultHttpClient class in my project.
it's would be easier if you change the $_POST to $_GET
but the problem in the $_GET method if the message have (&something=) inside
it you will receive only half the message as the &something= would be set to an other $_GET , Also you might get some problems if the message is too long ,
so if you want to use the $_POST method instead of the $_GET
you need to change your java code ,
make sure to import Map and then change it to this
void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
ParseUser currentUser = ParseUser.getCurrentUser();
StringBuilder messageBuilder = new StringBuilder();
for (int i=0; i<productsOrdered.size(); i++){
messageBuilder.append(productsOrdered.get(i)).append("\n");
}
String mess = messageBuilder.toString();
Map<String,Object> params = new LinkedHashMap<>();
params.put("name", currentUser.getString(Configurations.USER_FULLNAME));
params.put("fromEmail", fromEmail);
params.put("receiverEmail", receiverEmail);
params.put("messageBody", mess);
params.put("storeName", Configurations.MERCHANT_NAME);
params.put("shippingAddress", currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.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"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
String strURL = PHPfileUurl;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
} else {
InputStream err = conn.getErrorStream();
Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
}
} catch (IOException e) {e.printStackTrace(); }
}
Use $_GET instead of $_POST ,
change all variable from
$name = $_POST['name'];
to
$name = $_GET['name'];

Push notifications using google cloud messaging (gcm) in ios issue

I am trying to send notification message for IOS through GCM from JAVA. That time i am getting one error with 400 status code Bad Request. Below i have mentioned my JAVA code...
String apiKey = "xxxxxxxxxxxxxxxxxxxx"; // Put here your API key
String GCM_Token = regid; // put the GCM Token you want to send to here
String notification = "{\"sound\":\"default\",\"badge\":\"2\",\"title\":\"default\",\"body\":\"Test Push!\"}"; // put the message you want to send here
String messageToSend = "{\"to\":\"" + GCM_Token + "\",\"notification\":" + notification + ",\"content_available\" : true}"; // Construct the message.
TRY{
URL url = new URL("https://android.googleapis.com/gcm/send");
System.out.println("Message"+messageToSend);
// Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Set the headers
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(messageToSend.getBytes("UTF-8"));
//Send the request and close
wr.flush();
wr.close();
//Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Message : " + conn.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Print result
System.out.println(response.toString()); //this is a good place to check for errors using the codes in http://androidcommunitydocs.com/reference/com/google/android/gcm/server/Constants.html
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
please give me the suggestion.Thanks in advance.

Bearer Code returning HTTP 400 error for Twitter Search API V1.1

I am trying to implement the Twitter Search API V1.1
Please correct me if I am wrong.
I performed the below mentioned steps :
Step 1) Created an App in Twitter.
So I got the TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRETCODE.
Step 2) I encoded the concatenation of the above keys separated by ":" with the base UTF-8.
Step3 ) Get the bearer token with the above generated code.
Step4 ) Use the bearer code to get the Tweets on the relevance of a keyword.
I am stuck in Step 3,
where in I am getting the Response as::
Server returned HTTP response code: 400 for URL: https://api.twitter.com/oauth2/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.tcs.crm.socialCRM.action.TwitterIntegration.requestBearerToken(TwitterIntegration.java:74)
at com.tcs.crm.socialCRM.action.TwitterIntegration.getStatusSearch(TwitterIntegration.java:27)
at com.tcs.crm.socialCRM.action.TwitterIntegration.main(TwitterIntegration.java:103)
My code is ::
HttpsURLConnection connection = null;
PrintWriter outWriter = null;
BufferedReader serverResponse = null;
try
{
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Search Tweets");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
connection.setDoOutput( true );
logger.info("Point 1");
//CREATE A WRITER FOR OUTPUT
outWriter = new PrintWriter( connection.getOutputStream() );
logger.info("Point 2");
//SEND PARAMETERS
outWriter.println( "grant_type=client_credentials" );
outWriter.flush();
outWriter.close();
logger.info("Point 3");
//RESPONSE STREAM
serverResponse = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
JSONObject obj = (JSONObject)JSONValue.parse(serverResponse);
logger.info("The return string is "+obj.toString());
return obj.toString();
Please let me know how I can resolve this issue.
I had the same problem with the bearer token from Twitter. Also I test your same code and I received the error 403. After that I was creating my custom method to obtain the bearer token from twitter and I got the solution.
HttpClient httpclient = new DefaultHttpClient();
String consumer_key="YOUR_CONSUMER_KEY";
String consumer_secret="YOUR_CONSUMER_SECRET";
// Following the format of the RFC 1738
consumer_key=URLEncoder.encode(consumer_key, "UTF-8");
consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8");
String authorization_header_string=consumer_key+":"+consumer_secret;
byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes());
String encodedString = new String(encoded); //converting byte to string
HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token");
httppost.setHeader("Authorization","Basic " + encodedString);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Good luck!
The Twitter dev doc tells to give the "Content-Length":
https://dev.twitter.com/oauth/application-only
(see at "Example Result" below "Step 2: Obtain a bearer token")
However, in my case (with PHP), it works only if I remove "Content-Length".
I know this is rather late, but i found that the following worked for me (thanks #jctd_BDyn for the code to encode the key and secret for basic auth):
private String createBasicAuth() throws UnsupportedEncodingException {
String consumer_key="YOUR_CONSUMER_KEY";
String consumer_secret="YOUR_CONSUMER_SECRET";
// Following the format of the RFC 1738
consumer_key=URLEncoder.encode(consumer_key, "UTF-8");
consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8");
String authorization_header_string=consumer_key+":"+consumer_secret;
byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes());
return new String(encoded); //converting byte to string
}
private HttpURLConnection createBearerTokenConnection() throws IOException {
URL url = new URL("https://api.twitter.com/oauth2/token");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Authorization", "Basic " + createBasicAuth());
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String formData = "grant_type=client_credentials";
byte[] formDataInBytes = formData.getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write(formDataInBytes);
os.close();
log.info("Sending 'POST' request to URL : " + bearerTokenUrl);
return connection;
}
public Optional<BearerToken> getBearerToken() {
try {
HttpURLConnection connection = createBearerTokenConnection();
int responseCode = connection.getResponseCode();
log.info("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if (responseCode == 200) {
// Transforming from JSON string to POJO
return transformer.toBearerToken(response.toString());
} else {
log.error("Unexpected response code with response " + response.toString());
}
} catch (IOException e) {
log.error(String.format("IO exception on POST to %s", bearerTokenUrl), e);
}
return Optional.empty();
}

timestamp error bouncycastle

Im trying to get a timestamp from a tsa server and I got this error. I dont know where is the problem.
java.lang.IllegalArgumentException: unknown object in 'TimeStampResp' factory : org.bouncycastle.asn1.DERUnknownTag
In this statement
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
This is my code:
String TSA_URL = "http://tsa.starfieldtech.com/";
//String TSA_URL = "http://ca.signfiles.com/TSAServer.aspx";
//String TSA_URL = "http://timestamping.edelweb.fr/service/tsp";
try {
//byte[] digest = calcularMessageDigest(leerByteFichero("C:\\deskSign.txt"));
byte[] digest = leerByteFichero("C:\\deskSign.txt");
TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator();
TimeStampRequest req = reqgen.generate(TSPAlgorithms.SHA1, digest);
byte request[] = req.getEncoded();
URL url = new URL(TSA_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type:", "application/timestamp-query");
con.setRequestProperty("Content-length:", String.valueOf(request.length));
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
response.validate(req);
System.out.println(response.getTimeStampToken().getTimeStampInfo().getGenTime());
Anyone can help me?
You made two errors:
No colons after Content-type and Content-length
You forgot to actually send the request
Here is and adaptation of your code that works:
TimeStampRequest request;
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/timestamp-query");
con.setRequestProperty("Content-length", String.valueOf(request.getEncoded().length));
Authenticator.setDefault(new Authenticator() {
con.getOutputStream().write(request.getEncoded());
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);

Adding header for HttpURLConnection

I'm trying to add header for my request using HttpUrlConnection but the method setRequestProperty() doesn't seem working. The server side doesn't receive any request with my header.
HttpURLConnection hc;
try {
String authorization = "";
URL address = new URL(url);
hc = (HttpURLConnection) address.openConnection();
hc.setDoOutput(true);
hc.setDoInput(true);
hc.setUseCaches(false);
if (username != null && password != null) {
authorization = username + ":" + password;
}
if (authorization != null) {
byte[] encodedBytes;
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + encodedBytes;
hc.setRequestProperty("Authorization", authorization);
}
I have used the following code in the past and it had worked with basic authentication enabled in TomCat:
URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
You can try the above code. The code above is for POST, and you can modify it for GET
Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes variable is a byte[] and not a String value. If you pass the byte[] to a new String() as below, the code snippet works perfectly.
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);
If you are using Java 8, use the code below.
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);
Finally this worked for me
private String buildBasicAuthorizationString(String username, String password) {
String credentials = username + ":" + password;
return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}
Your code is fine.You can also use the same thing in this way.
public static String getResponseFromJsonURL(String url) {
String jsonResponse = null;
if (CommonUtility.isNotEmpty(url)) {
try {
/************** For getting response from HTTP URL start ***************/
URL object = new URL(url);
HttpURLConnection connection = (HttpURLConnection) object
.openConnection();
// int timeOut = connection.getReadTimeout();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
String authorization="xyz:xyz$123";
String encodedAuth="Basic "+Base64.encode(authorization.getBytes());
connection.setRequestProperty("Authorization", encodedAuth);
int responseCode = connection.getResponseCode();
//String responseMsg = connection.getResponseMessage();
if (responseCode == 200) {
InputStream inputStr = connection.getInputStream();
String encoding = connection.getContentEncoding() == null ? "UTF-8"
: connection.getContentEncoding();
jsonResponse = IOUtils.toString(inputStr, encoding);
/************** For getting response from HTTP URL end ***************/
}
} catch (Exception e) {
e.printStackTrace();
}
}
return jsonResponse;
}
Its Return response code 200 if authorizationis success
With RestAssurd you can also do the following:
String path = baseApiUrl; //This is the base url of the API tested
URL url = new URL(path);
given(). //Rest Assured syntax
contentType("application/json"). //API content type
given().header("headerName", "headerValue"). //Some API contains headers to run with the API
when().
get(url).
then().
statusCode(200); //Assert that the response is 200 - OK
It work for me.
I had to send request to another hand, and transfer header "Authorization" + jwt and some params via POST. By another side we formed jettyRequest with params and headers. If I send this sequence of code:
URL url = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)url.openConnection();
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty ("Authorization", jwt); // <---- this place
// some code add params
then I received only params in a body.
If I send this:
URL url = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)url.openConnection();
myURLConnection.setRequestProperty ("Authorization", jwt); // <---- this place
myURLConnection.setRequestMethod("POST");
// some code add params
then I received headers Authorization and params.
Step 1: Get HttpURLConnection object
URL url = new URL(urlToConnect);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
Step 2: Add headers to the HttpURLConnection using setRequestProperty method.
Map<String, String> headers = new HashMap<>();
headers.put("X-CSRF-Token", "fetch");
headers.put("content-type", "application/json");
for (String headerKey : headers.keySet()) {
httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
}
Reference link

Categories