Send push notification from server to android device in Java - java

I am struggling with the new FCM... I used FCM before, now I am trying FCM...
I am trying to send push notification for my app server to android device.
I wanna use the standard Java package, try not to use others such as Vert.x, apache's httpClient etc...
here is my code:
public void sendNotification(String messageBody)
{
try
{
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String apiKey = "AI...wE";
String credentials = "key=" + apiKey;
//String basicAuth = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
String basicAuth = "Basic " + new String(Base64.encodeBase64(credentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
String notfnStr = "{\"body\": \"this is my body\", \"title\": \"this is my title\"}";
String dataStr = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
String bodyStr = "{\"priority\": \"high\", \"to\": \"dFC8GW0N1Q8:APA91bHePPmC7QVV16LGnR6rqxwreHSv1GgawijZ_dZL9T70ZkiXIV8TW_ymAWkvFfXRiWJmtR_UGBXBv2iV2UhS8M-Tndw8sf8ZW6zIqfaiiVJao3G5HFbhqgA18ukNNtW_J7JaWkz8\", " +
"\"notification\": " + notfnStr + ", \"data\": " + dataStr + "}";
System.out.println("### input: " + bodyStr);
OutputStream os = conn.getOutputStream();
os.write(bodyStr.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
the response code i got is 401, which means unauthorized... i guess the format of credential is wrong...
The json string is in valid json format, so i don't bother to use JSONObject.
For the string credentials, i have tried "key:" + apiKey; but still got the same result.
The apiKey String is copied from the google-services.json I downloaded from Firebase console in google.
google didn't give a good example... just gave me this: https://firebase.google.com/docs/cloud-messaging/downstream
If any one knows how to do it, please reply. Thanks!!

FULL EXAMPLE USE THIS FOR SEND NOTIFICATION USING FCM IN JAVA
public class FCMNotification {
// Method to send Notifications from server to client end.
public final static String AUTH_KEY_FCM = "API_KEY_HERE";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static void pushFCMNotification(String DeviceIdKey) 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 data = new JSONObject();
data.put("to", DeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "FCM Notificatoin Title"); // Notification title
info.put("text", "Hello First Test notification"); // Notification body
data.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
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();
}
#SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
FCMNotification.pushFCMNotification("USER_DEVICE_TOKEN");
}
}

You mentioned that you got he key from the google-services.json file. That would be your Android API key, not the server key required to send FCM messages. In the Firebase console go to Settings > Cloud Messaging > Server key for the API key to be used for sending FCM messages.

This is a function using to send notification from java to the app android. this code use JSONObject you must add this jar into project buildpath.
note:I use fcm
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class FcmNotif {
public final static String AUTH_KEY_FCM ="AIzB***********RFA";
public final static String API_URL_FCM ="https://fcm.googleapis.com/fcm/send";
// userDeviceIdKey is the device id you will query from your database
public void pushFCMNotification(String userDeviceIdKey, String title, String message) 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", title); // Notification title
info.put("body", message); // Notification body
info.put("image", "https://lh6.googleusercontent.com/-sYITU_cFMVg/AAAAAAAAAAI/AAAAAAAAABM/JmQNdKRPSBg/photo.jpg");
info.put("type", "message");
json.put("data", info);
System.out.println(json.toString());
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}
}
good luck

As far as I know there is no need to base64 encode the credentials:
String apiKey = "AI...wE";
String credentials = "key=" + apiKey;
conn.setRequestProperty ("Authorization", credentials);

Related

How to send post request in java with a JSON body

I am confused as to how to send a post request in Java with JSON parameters. I have seen many examples that use HttpPost library which I can not access. Below is my code:
public class endpointtest {
public String endpoint(String urlStr, String username) {
final StringBuilder response = new StringBuilder();
try {
//creating the connection
URL url = new URL(urlStr);
HttpClient client = HttpClient.newHttpClient();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
//builds the post body, adds parameters
final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//out.writeBytes(toJSON(globalId));
out.flush();
out.close();
//Reading the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputline;
while ((inputline = in.readLine()) != null) {
response.append(inputline);
}
in.close();
connection.getResponseCode();
connection.disconnect();
} catch (final Exception ex) {
ex.printStackTrace();
System.out.println(" error ");
}
return response.toString();
}
}
class main {
public static void main(String[] args){
endpointtest ep = new endpointtest();
ep.endpoint("localhost:8080/endpoint","""
{
"name": "mike",
"Id": "123"
}
""");
}
}
I am trying to pass the json in the main method (I know I am not doing it right), and was wondering as to how I would do this correctly.
This is the simplest way to do it.
public class Main {
public static void main(String[] args) throws IOException {
String apiUrl = "http://myserver/rest/V1.0/manage/export"; // Your api/http link
String userName = "admin"; // Your username
String password = "adminpro"; // Your password
sendRequest(basicUrl, userName, password);
}
public static void sendRequest(String apiurl,String userName,String password){
try{
URL url = new URL(apiurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes()));
String payload = "{\"sampleKey\":\"sampleValue\"}";// This should be your json body i.e. {"Name" : "Mohsin"}
byte[] out = payload.getBytes(StandardCharsets.UTF_8);
OutputStream stream = connection.getOutputStream();
stream.write(out);
System.out.println(connection.getResponseCode() + " " + connection.getResponseMessage()); // THis is optional
connection.disconnect();
}catch (Exception e){
System.out.println(e);
System.out.println("Failed successfully");
}
}
}
This Question is asked before here:
HTTP POST using JSON in Java
See it and comment this if you face any problem.

Trying to get an Access Token from Dwolla restful api

Im having trouble getting an access token for the sandbox environment.
Im following this guide for authenticating: OAuth
So when i create my request, following this guide, i get the following response from the api:
{"error":"access_denied","error_description":"Invalid application credentials."}
Im using key for mf client ID and secret as my client secret as per the instructions.
Here is the code Im using:
public static void main(String[] args) {
try {
URL url = new URL("https://www.dwolla.com/oauth/v2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("client_id", "<Key>");
conn.setRequestProperty("client_secret", "<Secret>");
conn.setRequestProperty("grant_type", "client_credentials");
conn.setDoInput(true);
conn.setDoOutput(true);
System.out.println("Message:" + conn.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException ex) {
Logger.getLogger(PaymentTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PaymentTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
I was able to get an access token finally. My problem is first of all the above code uses client_id and client_secret as header params. These need to go in the body of the request.
My second problem is that I used the wrong content type for the message I was sending.
Here is the code that worked for me:
URL url = new URL("https://sandbox.dwolla.com/oauth/v2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String data = "";
JSONObject jsonObj = new JSONObject();
jsonObj.put("client_id", "<Your Client ID>");
jsonObj.put("client_secret", "<Your Client Secret>");
jsonObj.put("grant_type", "client_credentials");
data = jsonObj.toString();
System.out.println("data = " + data);
byte[] outputInBytes = data.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
System.out.println("Message:" + conn.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();

How to setEntity on a HttpURLConnection

In my project I must strictly use HttpURLConnection class
I have this following code which I got from the internet
MultipartEntity multiPart = new MultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null Chartset.forName("UTF-8");
File f = new File("/home/abhishek/foo.docx");
FileBody fb = new FileBody(f);
multiPart.addPart("file", fb);
HttpPost post = new HttpPost();
post.setHeader("ENCTYPE", "multipart/form-data");
post.setEntity(multiPart);
Problem is that I cannot use HttpPost ... In my project only HttpURLConnection class works!
So I need to translate the code above into HttpURLConnection.
I cannot find anything similar to setEntity on the HttpUrlConnection.
Edit::
Based on the suggestions below. I have this code
public class RESTFileUpload {
public static void main(String[] args) throws Exception {
Authenticator.setDefault(new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("domain\\user", "Password".toCharArray());
}
});
String filePath = "/home/abhishek/Documents/HelloWorld.docx";
String fileName = "HelloWorld.docx";
String fileNameShort = "HelloWorld";
String urlStr = "https://sp.company.com/sites/abhi_test/_vti_bin/listdata.svc/SharedDocuments/RootFolder/Files/add(url=#TargetFileName,overwrite='true')&#TargetFileName=" + fileName;
String crlf = "\r\n";
String twoHypens = "--";
String boundary = "*****";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(con.getOutputStream());
request.writeBytes(twoHypens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data;name=\"" + fileNameShort + "\";fileName=\"" + fileName + "\"" + crlf);
request.writeBytes(crlf);
request.write(convertToByteArray(filePath));
request.writeBytes(crlf);
request.writeBytes(twoHypens + boundary + twoHypens + crlf);
request.flush();
request.close();
InputStream responseStream = new BufferedInputStream(con.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder strBuilder = new StringBuilder();
while((line = responseStreamReader.readLine()) != null) {
strBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = strBuilder.toString();
responseStream.close();
con.disconnect();
System.out.println(response);
}
private static byte[] convertToByteArray(String filePath) {
File f = new File(filePath);
byte[] retVal = new byte[(int)f.length()];
try {
FileInputStream fis = new FileInputStream(f);
fis.read(retVal);
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch(IOException ex2) {
ex2.printStackTrace();
}
return retVal;
}
}
But I get the error
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://sp.web.gs.com/sites/abhi_test/_vti_bin/listdata.svc/SharedDocuments/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at RESTFileUpload.main(RESTFileUpload.java:62)
HttpURLConnection has .getInputStream() and .getOutputStream() methods. If you wish to send body content with an Http request, you call .setDoOutput(true) on your HttpURLConnection object, call .getOutputStream() to get an Output stream and then write the content of your entity to the output stream (either as raw bytes, or using a Writer implementation of some sort), closing it when you are finished writing.
For more details, see the API docs for HttpURLConnection here.
To post files using the HttpURLConnection you have to compose the file wrapper manually. Take a look at this answer, it should be helpful for you.

Java: how to use UrlConnection to post request with authorization?

I would like to generate POST request to a server which requires authentication. I tried to use the following method:
private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
String data = "product[title]=" + URLEncoder.encode(title) +
"&product[content]=" + URLEncoder.encode(content) +
"&product[price]=" + URLEncoder.encode(price.toString()) +
"&tags=" + tags;
try {
URL url = new URL(urlString);
URLConnection conn;
conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
return rd.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
and the line
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
also throws an IOException.
Anyway I would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using POST with UrlConnection.
but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection to HttpURLConnection, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
I don't see anywhere in the code where you specify that this is a POST request. Then again, you need a java.net.HttpURLConnection to do that.
In fact, I highly recommend using HttpURLConnection instead of URLConnection, with conn.setRequestMethod("POST"); and see if it still gives you problems.
To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me
Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback
BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work.
Inside my servlet to do GET using url like
e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked
Thanks to all contributors
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> 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");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
To send a POST request call:
connection.setDoOutput(true); // Triggers POST.
If you want to sent text in the request use:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
wr.write(textToSend);
wr.flush();
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
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();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
and Just call the function when you needed to get the data from server either by post or get like this
HashMap<String, String>params = new HashMap<String, String>();
params.put("action", "request_sample");
params.put("name", uname);
params.put("message", umsg);
params.put("email", getEmailofUser());
params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
#Override
public void onSucess(Bundle bundle) {
debug("data", bundle.getString(DbConstants.RESPONSE));
}
#Override
public void onFailed(int status_code, String mesage, String url) {
debug("sample", mesage);
}
});
Now it is complete.Enjoy!!! Comment it if find any problem.
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
i was looking information about how to do a POST request. I need to specify that mi request is a POST request because, i'm working with RESTful web services that only uses POST methods, and if the request isn't post, when i try to do the request i receive an HTTP error 405. I assure that my code isn't wrong doing the next: I create a method in my web service that is called through GET request and i point my application to consume that web service method and it works.
My code is the next:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());

Connecting to remote URL which requires authentication using Java

How do I connect to a remote URL in Java which requires authentication. I'm trying to find a way to modify the following code to be able to programatically provide a username/password so it doesn't throw a 401.
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
There's a native and less intrusive alternative, which works only for your call.
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
You can set the default authenticator for http requests like this:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)
You can also use the following, which does not require using external packages:
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.
Sample URL: http://user:pass#example.com/url
URL url = new URL("http://user:pass#example.com/url");
URLConnection urlConnection = url.openConnection();
if (url.getUserInfo() != null) {
String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
InputStream inputStream = urlConnection.getInputStream();
Please note in the comment, from valerybodak, below how it is done in an Android development environment.
As I have came here looking for an Android-Java-Answer I am going to do a short summary:
Use java.net.Authenticator as shown by James van Huis
Use Apache Commons HTTP Client, as in this Answer
Use basic java.net.URLConnection and set the Authentication-Header manually like shown here
If you want to use java.net.URLConnection with Basic Authentication in Android try this code:
URL url = new URL("http://www.example.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc
Was able to set the auth using the HttpsURLConnection
URL myUrl = new URL(httpsURL);
HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//httpsurlconnection
conn.setRequestProperty("Authorization", basicAuth);
few of the changes fetched from this post. and Base64 is from java.util package.
Be really careful with the "Base64().encode()"approach, my team and I got 400 Apache bad request issues because it adds a \r\n at the end of the string generated.
We found it sniffing packets thanks to Wireshark.
Here is our solution :
import org.apache.commons.codec.binary.Base64;
HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());
private String getBasicAuthenticationEncoding() {
String userPassword = username + ":" + password;
return new String(Base64.encodeBase64(userPassword.getBytes()));
}
Hope it helps!
Use this code for basic authentication.
URL url = new URL(path);
String userPass = "username:password";
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or
//String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.connect();
Since Java 9, you can do this
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setAuthenticator(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("USER", "PASS".toCharArray());
}
});
I'd like to provide an answer for the case that you do not have control over the code that opens the connection. Like I did when using the URLClassLoader to load a jar file from a password protected server.
The Authenticator solution would work but has the drawback that it first tries to reach the server without a password and only after the server asks for a password provides one. That's an unnecessary roundtrip if you already know the server would need a password.
public class MyStreamHandlerFactory implements URLStreamHandlerFactory {
private final ServerInfo serverInfo;
public MyStreamHandlerFactory(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
#Override
public URLStreamHandler createURLStreamHandler(String protocol) {
switch (protocol) {
case "my":
return new MyStreamHandler(serverInfo);
default:
return null;
}
}
}
public class MyStreamHandler extends URLStreamHandler {
private final String encodedCredentials;
public MyStreamHandler(ServerInfo serverInfo) {
String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
}
#Override
protected URLConnection openConnection(URL url) throws IOException {
String authority = url.getAuthority();
String protocol = "http";
URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());
HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
return connection;
}
}
This registers a new protocol my that is replaced by http when credentials are added. So when creating the new URLClassLoader just replace http with my and everything is fine. I know URLClassLoader provides a constructor that takes an URLStreamHandlerFactory but this factory is not used if the URL points to a jar file.
i did that this way you need to do this just copy paste it be happy
HttpURLConnection urlConnection;
String url;
// String data = json;
String result = null;
try {
String username ="user#gmail.com";
String password = "12345678";
String auth =new String(username + ":" + password);
byte[] data1 = auth.getBytes(UTF_8);
String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
//Connect
urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+base64);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
JSONObject obj = new JSONObject();
obj.put("MobileNumber", "+97333746934");
obj.put("EmailAddress", "danish.hussain#example.com");
obj.put("FirstName", "Danish");
obj.put("LastName", "Hussain");
obj.put("Country", "BH");
obj.put("Language", "EN");
String data = obj.toString();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
ANDROD IMPLEMENTATION
A complete method to request data/string response from web service requesting authorization with username and password
public static String getData(String uri, String userName, String userPassword) {
BufferedReader reader = null;
byte[] loginBytes = (userName + ":" + userPassword).getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", loginBuilder.toString());
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null){
sb.append(line);
sb.append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories

Resources