HttpURLConnection - returned format - java

I'm using HttpUrlConnection to consume REST services. When I do GET, like the one I show below, I don't want to get the information that is returned char by char. I want to get the result in the format that it is returned. Here, for example, I want to get a boolean, and not something like System.out.print((char) ch);. How can I receive it?
I know that I can parse a String into a Boolean type, but if I receive another data type?
public class SensorGetDoorStatus {
public static void main(String[] args) throws Exception
{
HttpURLConnection urlConnection = null;
try {
String webPage = "http://localhost:8080/LULServices/webresources/services.sensors/doorstatus";
String name = "xxxx";
String password = "xxxx";
Authenticator myAuth = new Authenticator()
{
final String USERNAME = "xxxx";
final String PASSWORD = "xxxxx";
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
}
};
Authenticator.setDefault(myAuth);
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL urlToRequest = new URL(webPage);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
System.out.println("Authorization : Basic " + authStringEnc);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setReadTimeout(15*1000);
urlConnection.connect();
InputStream inStrm = urlConnection.getInputStream();
int ch;
while (((ch = inStrm.read()) != -1))
System.out.print((char) ch);
inStrm.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Failure processing URL");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
}

I'd play around with BufferedReader: it allows to read an InputStream line by line, and you might be able to parse your data that way.
If your data is in a predefined format like XML or JSON, you'd better use a library to parse your response data, though.

You might want to look at using DataInputStream. You can use the method readBoolean method of this class to read a boolean.
The DataInputStream and DataOutputStream also provides you with methods to write and read specific data types for example int, float, long etc
You should have written writeBoolean of class DataOutputStream on the other end from where you are sending data.
The code will look like follwoing:
InputStream inStrm = urlConnection.getInputStream();
DataInputStream doi = new DataInputStream(inStrm);
boolean bol = doi.readBoolean();
doi.close();
inStrm.close();

Related

How to send request from android to servlet with parameters

I am trying to send a request from my android device to servlet with parameters and parameters are sending as part of the request.
I have a button on clicking on that I get the text from editText views modify my url to make a url with parameters and send that url to AsyncTask.
Here is my code.
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringUrl = "http://192.168.11.4:8084/WebApplication1/DemoServlet?email=" + editTextEmail.getText() + "&password=" + editTextPassword.getText() + "&phone=" + editTextPhoneNumber.getText();
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new RegistrationTask().execute(stringUrl);
} else {
Toast.makeText(RegisterActivity.this, "Error!. Please check your internnet connection", Toast.LENGTH_SHORT).show();
}
}
});
}
And here is my RegistrationTask code.
class RegistrationTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return getResponse(params[0]);
}
#Override
protected void onPostExecute(String result) {
editTextEmail.setText(result);
}
public String getResponse(String myurl) {
InputStream is = null;
String contentAsString = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d("Download", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
contentAsString = readIt(is, len);
return contentAsString;
} catch (Exception e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return contentAsString;
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
I tried to debug my servlet code but request coming as email=password=phone=
Please help me to sort it out.
Not an answer, but would help you.
First please share the servlet code too
Second, encode parameter using URLEncoder.encode(arg:String):String before sending the request, such as following
String stringUrl = "http://192.168.11.4:8084/WebApplication1/DemoServlet?email="
+URLEncoder.encode(editTextEmail.getText())
Also your method readIt(stream:InputStream,len:int):String is not reliable because of the way yo read the info.
Note that InputStream.read(buf::byte[]):int would not fill the whole buffer even if too much data is available, and the int response indicates the number of data was written to the buffer, so your code would get data inconsistency.
You may using DataInputStream.readFully(buff:byte[]):void which either fills the buffer completely or throws exception when there are not enough data.
Or better way read till EOS, where read() method returns -1.

httpsurlconnection posts string wrongly in java application

In my java application I used a Httpsurlconnection to post some string data to the server. When I test this code on android, it works perfectly. However, in a java application it does not work. Client java application is as follows:
public static void main(String[] args) {
disableSslVerification();
new HttpsClient().testIt();
}
private void testIt() {
String https_url = "https://XXX.XX.XXX.XXX:XXXX/XXXXX/TestServlet";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
print_content(con, "test");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void print_content(HttpsURLConnection connection, String data) {
if (connection != null) {
try {
connection.setConnectTimeout(6000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
Charset cSet = Charset.forName("UTF-8");
byte bytes[] = data.getBytes(cSet);
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(bytes.length));
connection.setRequestProperty("Content-Language", "tr");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.write(bytes);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, cSet));
String line;
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append(System.getProperty("line.separator"));
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
And the servlet is as follows:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s = getHTML(request);
try {
out.print("received data:");
out.print(s);
} finally {
out.close();
}
}
private String getHTML(HttpServletRequest request) throws IOException {
int n = request.getContentLength();
if (n < 1) {
return "";
}
byte bytes[] = new byte[n];
request.getInputStream().read(bytes);
return new String(bytes, "UTF-8");
}
When I run this application, servlet's response is:
received data:t☐☐☐
Always only the first character is correctly send to the servlet. The same code works perfect on android. Can anyone help me please? Thanks...
I can't see an obvious problem with your code that would cause this.
Can anyone help me please?
I suggest that you take a methodical approach to investigating the problem. Use a packet sniffer to check what is actually being sent over the wire. Check that the actual headers in the request and response are correct. Check that the request and response bodies are really properly encoded UTF-8 ...
What you find in your investigation / evidence gathering will help you figure out where the problem (or problems) are occurring ... and that will allow you to home in on the part(s) of your code that is/are responsible.
request.getInputStream().read(bytes);
You might need to do this read in a loop. At the very least, check how many bytes have been read. The array appears to be empty except for the first char.
Reads some number of bytes from the input stream and stores them into
the buffer array b. The number of bytes actually read is returned as
an integer. This method blocks until input data is available, end of
file is detected, or an exception is thrown.

InputStream being lost

I have a class titled: ServiceCaller.java
This class contains a method used to call web services:
public static Response callService(String strURL, String Token, int timeout, Boolean isPostMethod) {
String error = "";
int statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
HttpURLConnection urlConnection = null;
try
{
URL url = new URL(strURL);
// Allow non trusted ssl certificates
if(strURL.startsWith("https"))
{
TrustManagerManipulator.allowAllSSL();
}
urlConnection = (HttpURLConnection) url.openConnection();
if (isPostMethod) {
urlConnection.setRequestMethod("POST");
}
else {
urlConnection.setRequestMethod("GET");
}
// Allow Inputs
urlConnection.setDoInput(true);
// Allow Outputs
urlConnection.setDoOutput(true);
// Don't use a cached copy.
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Token", Helpers.getUTF8Encode(Token));
urlConnection.setConnectTimeout(timeout);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
dos.flush();
dos.close();
statusCode = urlConnection.getResponseCode();
Response r = new Response(statusCode, urlConnection.getInputStream(), "No Exception");
return r;
} catch (Exception ex) {
error = ex.getMessage();
if (error != null && !error.equals("") && error.contains("401"))
statusCode = HttpStatus.SC_UNAUTHORIZED;
} finally {
urlConnection.disconnect();
}
return new Response(statusCode, null, error);
}
Here's the Response class:
public static class Response
{
private int statusCode;
private InputStream responseStream;
private String exception;
public int getStatusCode() {
return statusCode;
}
public InputStream getResponseStream() {
return responseStream;
}
public String getExceptionError() {
return exception;
}
public Response(int code, InputStream stream, String strException)
{
this.statusCode = code;
this.responseStream = stream;
this.exception = strException;
}
}
This is the Test class that I use to test the function in ServiceCaller:
public class TestDemo {
private static final String EncriptionKey = "keyValueToUse";
public static void main(String[] args) {
try {
String strURL = "http://...";
String strURL2 = "http://...";
String Token = "iTcakW5...";
int timeout = 120000;
Boolean isPostMethod = true;
ServiceCaller.Response resp = ServiceCaller.CallService(strURL2, Token, timeout, isPostMethod);
InputStream inputStream = resp.getResponseStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String resultJSON = writer.toString();
System.out.println("Status Code: " + resp.getStatusCode());
System.out.println("JSON String:\n" + resultJSON);
System.out.println("Exception: " + resp.getExceptionError());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here's the Output of executing hte previous code:
Status Code: 200
JSON String:
Exception: No Exception
Here's the problem, the InputString that is returned in the Test class appears to be empty because the conversion to string returns an empty string BUT if I do the same code to convert the InputString inside the CallService function then the conversion is successful, also note that the Status Code and Exception (strings) are being returned correctly.
public static Response CallService(String strURL, String Token, int timeout, Boolean isPostMethod) {
HttpURLConnection urlConnection = ...
...
new Response(statusCode, urlConnection.getInputStream(), "No Exception");
}
This code missing in the ... is probably the most important part. I guess you are closing the HttpURLConnection before returning back to the caller. How you do this can vary:
You simply close it before the return
try-catch-finally: You are closing it in the finally block.
you are using a try-with-resource construction as introduced in Java 7. The HttpURLConnection might be getting closed automatically. This is more unlikely since HttpURLConnection does not implement AutoClosable.
I've solved by first getting the InputStream from HttpURLConnection, then converting it to a byte array, then putting that byte array into a ByteArrayInputStream
byte[] bytes = IOUtils.toByteArray(urlConnection.getInputStream());
ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
return new Response(statusCode, byteStream, "");
According to the documentation a ByteArrayInputStream:
public ByteArrayInputStream(byte[] buf) Creates a ByteArrayInputStream
so that it uses buf as its buffer array. The buffer array is not
copied. The initial value of pos is 0 and the initial value of count
is the length of buf. Parameters: buf - the input buffer.
The problem is that you are already consuming the InputStream in your CallService method
statusCode = urlConnection.getResponseCode();
Response resp = new Response(statusCode, urlConnection.getInputStream(), "");
InputStream inputStream = resp.getResponseStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer); // consuming the stream
String resultJSON = writer.toString(); // you never use this, so why is it here?
So when you try to read from it again in main() there are no bytes left.
You can only read bytes from it once.
This doesn't throw any exceptions because IOUtils simply calls InputStream#read(...) which returns -1 if the EOF has been reached.
Note that Java naming convention states that method names should start with a lowercase character.

login and download a webpage with java and storing cookies

I'm having trouble logging into my schools moodle webpage and downloading the source code,
so far i am able to receive the login page it never actually logs in,
any help would be greatly appreciated i have been stuck with this problem for a couple of weeks now.
The code below is a not my own but a modified version of multiple examples that i have found on the web.
import java.net.*;
import java.io.*;
import java.util.*;
public class LoginByHttpPost
{
private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String LOGIN_USER_NAME = "myusername";
private static final String LOGIN_PASSWORD = "mypassword";
private static final String LOGIN_DOMAIN = "students.ltu.edu.au";
private static final String TARGET_URL = "https://www.latrobe.edu.au/lms/login/";
private String page ="";
public static void main (String args[])
{
LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost();
httpUrlBasicAuthentication.httpPostLogin();
}
public void httpPostLogin ()
{
try
{
String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD, LOGIN_DOMAIN);
HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
page = readResponse(urlConnection);
System.out.println("Successfully made the HTPP POST.");
System.out.println("Recevied response is: '/n" + page + "'");
}
catch(IOException ioException)
{
System.out.println("Problems encounterd.");
}
}
private String preparePostContent(String loginUserName, String loginPassword, String loginDomain) throws UnsupportedEncodingException
{
String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
String encodedLoginDomain = URLEncoder.encode(loginDomain, "UTF-8");
String content = URLEncoder.encode("username=", "UTF-8") + encodedLoginUserName
+ URLEncoder.encode("&password=", "UTF-8") + encodedLoginPassword
+ URLEncoder.encode("&domain=", "UTF-8") + encodedLoginDomain
+ URLEncoder.encode("&Login=", "UTF-8") + URLEncoder.encode("Login", "UTF-8");
return content;
}
public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
{
DataOutputStream dataOutputStream = null;
HttpURLConnection conn = null;
String cookieFirst = null;
String cookieValue = null;
String totalCookie = "";
try
{
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL(targetUrl);
conn = (HttpURLConnection)url.openConnection();
conn.getContent();
CookieStore cookiejar = manager.getCookieStore();
List<HttpCookie> cookiesList = cookiejar.getCookies();
for(HttpCookie cookiel: cookiesList)
{
totalCookie += cookiel+"; ";
}
totalCookie = totalCookie.substring(0, totalCookie.length()-1);
System.out.println("Total Cookie: " + totalCookie);
}
catch(Exception e)
{
System.out.println("Something went wrong");
}
HttpURLConnection urlConnection = null;
try{
URL url = new URL(targetUrl);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(true);
urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
urlConnection.setRequestProperty("Content-Length", Integer.toString(content.length()));
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Cookie", totalCookie);
urlConnection.connect();
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
}
catch(IOException ioException)
{
System.out.println("I/O problems while trying to do a HTTP post.");
ioException.printStackTrace();
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch(Throwable ignore)
{
}
}
if (urlConnection != null)
{
urlConnection.disconnect();
}
throw ioException;
}
return urlConnection;
}
private String readResponse(HttpURLConnection urlConnection) throws IOException
{
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String responeLine;
StringBuilder response = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null)
{
response.append(responeLine + "\n");
}
return response.toString();
}
catch(IOException ioException)
{
System.out.println("Problems while reading the response");
ioException.printStackTrace();
throw ioException;
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch(Throwable ignore)
{
}
}
}
}
}
To access this web page and log in, you're using a web browser and not a sequance of telnet commands, because it's much easier, right? Then, as a programmer, do the same and use a programmatic web browser rather than a sequence of low-level actions using cookies and URL connections. It will also be much easier.
HtmlUnit is such a programmatic web browser. The end of its Getting started page shows an example of loading a web page and submitting a form. HtmlUnit will handle the submission, cookie handling, encoding, etc. for you.

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