I am hitting HTTP url with username:password using JAVA code. Below is my code
public static main (String args[]){
try{
String webPage = "http://00.00.000.000:8080/rsgateway/data/v3/user/start/";
String name = "abc001";
String password = "abc100";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization","Basic " +authStringEnc);
connection.setRequestProperty("Accept", "application/xml");
connection.setRequestProperty("Content-Type", "application/xml");
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (Exception e) {
e.printStackTrace();
}
}
But I am getting 401 Error
java.io.IOException: Server returned HTTP response code: 401 for URL:
same url if i hit using curl then it is returning response. below is the curl command.
curl -u abc001:abc100 http://00.00.000.000:8080/rsgateway/data/v3/user/start/
Please help me resolve this.
The code you are getting is HTTP 401 Unauthorized, which means that the server isn't interpreting your basic authentication properly.
Since you say that the curl command with the basic authentication you showed is working, I'll assume the problem is in your code.
It looks like you tried to follow this code.
The only error I can see (but I cannot test this to be sure) is that you just cast the byte[] to a String instead of encoding it with Base64.
So you should change this:
String authStringEnc = new String(authEncBytes);
to this:
String authStringEnc = Base64.getEncoder().encodeToString(authEncBytes);
Also, you want to change this:
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
to this:
byte[] authEncBytes = authString.getBytes();
byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);
Related
I have a webservice whose content type is application/vnd.oracle.adf.resourceitem+json.
The HttpEntity of the reponse obtained by hitting this service is looks like this
ResponseEntityProxy{[Content-Type: application/vnd.oracle.adf.resourceitem+json,Content-Length: 3,Chunked: false]}
When I try to convert this HttpEntity into String it gives me a blank String {}.
Below are the ways I tried to convert the HttpEntity to String
1.
String strResponse = EntityUtils.toString(response.getEntity());
2.
String strResponse = "";
String inputLine;
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
try {
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
strResponse += inputLine;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
3.
response.getEntity().writeTo(new FileOutputStream(new File("C:\\Users\\harshita.sethi\\Documents\\Chabot\\post.txt")));
All returns String -> {}.
Can anyone tell me what am I doing wrong?
Is this because of the content type?
The above code is still giving the same response with empty JSON object. So I modified and wrote the below code. This one seems to run perfectly fine.
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization", getAuthToken());
con.addRequestProperty("Content-Type", "application/vnd.oracle.adf.resourceitem+json;charset=utf-8");
String input = String.format("{\"%s\":\"%s\",\"%s\":\"%s\"}", field, value, field2, value2);
System.out.println(input);
OutputStream outputStream = con.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
con.connect();
System.out.println(con.getResponseCode());
// Uncompressing gzip content encoding
GZIPInputStream gzip = new GZIPInputStream(con.getInputStream());
StringBuffer szBuffer = new StringBuffer();
byte tByte[] = new byte[1024];
while (true) {
int iLength = gzip.read(tByte, 0, 1024);
if (iLength < 0) {
break;
}
szBuffer.append(new String(tByte, 0, iLength));
}
con.disconnect();
returnString = szBuffer.toString();
Authentication method
private String getAuthToken() {
String name = user;
String pwd = this.password;
String authString = name + ":" + pwd;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
System.out.println(new String(authEncBytes));
return "Basic " + new String(authEncBytes);
}
In case anybody faces the same issue. Let me share the challenged I faced and how I rectified those.
The above code works for all content-types/methods. Can be used for any type (GET, POST, PUT,DELETE).
For my requirement I had a POST webservice with
Content-Encoding →gzip
Content-Type →application/vnd.oracle.adf.resourceitem+json
Challenges : I was able to get the correct response code but I was getting junk characters as my response string.
Solution : This was because the output was compressed in gzip format which needed to be uncompressed.
The code of uncompressing the gzip content encoding is also mentioned above.
Hope it helps future users.
Im trying to get all the xml data from a myanimelist request.
I've ried this code (see code below) on an other url and this worked.
Now, for myanimelist you need an account to request queries. I have tried different things like changing the location of uc.setRequestProperty ("Authorization", getBasicAuthenticationEncoding()); before and after the openConnection(); But nothing seems to work. The code below gives me this error: server returned HTTP response code: 401 for URL: http.
Can someone help me with this?
Code: (i used fake pwds for the example)
System.out.println(getXMLFromUrl("https://myanimelist.net/api/anime/search.xml?q=" + "2017"));
private String getBasicAuthenticationEncoding() {
String username= "username";
String password = "mypwd";
String userPassword = username + ":" + password;
#SuppressWarnings("static-access")
String basicAuth = "Basic " + new String(new Base64().encode(userPassword.getBytes()));
return basicAuth;
}
public String getXMLFromUrl(String url) throws IOException {
URL u = new URL(url);
URLConnection uc = u.openConnection();
uc.setRequestProperty ("Authorization", getBasicAuthenticationEncoding());
InputStream in = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
I am trying to send a request to get public transport information. Here's a screenshot of an example below, stating that I must send an XML request to the site, defining the method and the service reference (in the example it's StopMonitoringRequest and 020035811).
So far I have managed to connect to the service, but I have no idea what to do from here. I have so far done this...
String user = "";
String pass = "";
String url = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
String authString = user + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestMethod("POST");
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty( "charset", "utf-8");
connection.setUseCaches(false);
connection.setDoOutput(true);
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.print(result);
...receiving this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Siri version="1.0" xmlns="http://www.siri.org.uk/">
<ServiceDelivery>
<ResponseTimestamp>2015-11-08T20:33:03.574Z</ResponseTimestamp>
</ServiceDelivery>
</Siri>
How do I enter the required parameters and method?
So what I had to do was create a HttpPost and set the xml request up as an entity, binding it to the post. Here is the code, in case anyone wants to request information via HTTP POST using XML, outputting the XML as a string:
// basic autthorization security
String url = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
String authString = "<username>:<password>";
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Basic " + authStringEnc);
StringEntity input = new StringEntity(request);
input.setContentType("text/xml");
post.setEntity(input);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String unformattedXML = EntityUtils.toString(entity);
i have to retrive a csv using https protocol and Basic Authentication in java. i used this code but the output stream retrived is an array with 250 zero. there are some error in my code?
String webPage = url_a;
String name = email;
String password = pass;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.addRequestProperty("Authorization", "Basic " + authStringEnc);
urlConnection.setRequestMethod("POST");
urlConnection.setAllowUserInteraction(false);
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
final OutputStream outs = urlConnection.getOutputStream();
If you're trying to read the response, try urlConnection.getInputStrem() ...
The names input/output are viewed from your point of view (as client). So output is what you send out to server, and input is what you receive from server.