Servlet Exception java.io.filenotfoundexception inputstream - java

I have an exception thrown when launching the servelt doPost java.io.filenotfoundexception http://intssneip01.ppmail.ppservices.axa-tech.intraxa:5510/ws/fr-eda-pushevent-v1-vs
It occurs on the line inputstream getInputStream, here is the code:
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(backUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
String line = "";
StringBuffer sb = new StringBuffer();
BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()) );
while((line = input.readLine()) != null)
sb.append(line);
input.close();

Related

Microsoft graph search feature Java

I'm trying to use Microsoft Graph to make a file search. I use this entry point : https://graph.microsoft.com/beta/search/query
My application do not use a user account but a daemon with an application key (see auth method).
And i send a built object.
My java code is rather simple :
public static void main(String[] args) throws Exception{
try {
// Authentication result containing token
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
String token = result.accessToken();
SearchDocumentResponseModel documentQuery = fileGraphs.searchDocument(token, QUERYSTRING, 0, 25);
System.out.println("Find a document" + documentQuery.toString());
} catch(Exception ex){
throw ex;
}
}
private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ConfidentialClientApplication app = ConfidentialClientApplication.builder(
CONFIDENTIAL_CLIENT_ID,
ClientCredentialFactory.createFromSecret(CONFIDENTIAL_CLIENT_SECRET))
.authority(TENANT_SPECIFIC_AUTHORITY)
.build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(GRAPH_DEFAULT_SCOPE))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
The SearchDocumentResponseModel is just a set of POJO that build for me the object that i must send as a request body.
{
"requests":
[{
"entityTypes":["microsoft.graph.driveItem"],
"query":{"query_string":{"query":"any query"}},
"from":0,"size":25
}]
}
The method searchDocument is just here to build the object before i send it to the API
public SearchDocumentResponseModel searchDocument(String accessToken, String stringSearch, int from, int size) throws IOException {
SearchDocumentRequestModel searchRequest = new SearchDocumentRequestModel();
// set values here
...
URL url = new URL("https://graph.microsoft.com/beta/search/query");
return requestsBuilder.buildPostRequest(accessToken, searchRequest, url)
}
Now i want to send to server the Json and expect an answer :
public SearchDocumentResponseModel buildPostRequest(String accessToken, SearchDocumentRequestModel searchRequest, URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// write the input json in a string
String jsonInputString = new Gson().toJson(searchRequest);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
String httpResponseMessage = conn.getResponseMessage();
// reading the response
try(BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
String outputResponse = response.toString();
return new Gson().fromJson(outputResponse, SearchDocumentResponseModel.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I think i set the properties correctly. Is it coming from my code or from Microsoft Graph ? Thanks !
First of all, you should check if the access token is valid, you can send a request using postman.
If the token is valid, I think it should be the problem of your jsonInputString. The following code works fine.
URL url = new URL("https://graph.microsoft.com/beta/search/query");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "access_token" );
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String str = "";
str += "{";
str += " \"requests\": [";
str += " {";
str += " \"entityTypes\": [";
str += " \"microsoft.graph.driveItem\"";
str += " ],";
str += " \"query\": {";
str += " \"query_string\": {";
str += " \"query\": \"contoso\"";
str += " }";
str += " },";
str += " \"from\": 0,";
str += " \"size\": 25";
str += " }";
str += " ]";
str += "}";
OutputStream os = conn.getOutputStream();
byte[] input = str.getBytes("UTF-8");
os.write(input, 0, input.length);
System.out.println(conn.getResponseCode());
Update:
Query api doesn't support client credential flow.

Login twitter with username and password, POST java

I get OAuthToken, Authenticity Token from the libarary Twitter4j (it is correctly, becouse when I login in browser its works). Then try to login twiiter with password and username with POST request:
URL url = new URL("https://api.twitter.com/oauth/authorize");
Add parametrs to request:
String params = "oauth_token" + "=" + oAuthToken;
params += "&" + "session[username_or_email]" + "=" + login;
params += "&" + "session[password]" + "=" + password;
params += "&" + "redirect_after_login" + "=" + "https://twitter.com/oauth/authorize?oauth_token=" + oAuthToken;
params += "&" + "authenticity_token" + "=" + authToken;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream());
output.write(params);
output.flush();
get response:
StringBuilder sb = new StringBuilder();
int httpResult = connection.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
br.close();
PrintWriter out = new PrintWriter("response.html");
out.print(sb);
out.close();
out.flush();
System.out.println(getVerifier(sb.toString()));
} else {
System.out.println("Response: " + connection.getResponseMessage() + ", Status: " + httpResult);
}
But nothing happens, in response I have HTML page, where I can login twitter.

sending chinese text in post method in java

I need to send some Chinese and Korean text to a server using a post request in java. I have tried the following but it does not work.What I receive on server side are junk or '????'.
public static String HttpPostGeneric(String URLstr, String[] paramName, String[] paramVal)
{
try{
String parameters = null;
if ((paramName != null ) && (paramVal != null))
{
parameters = paramName[0] +"="+ paramVal[0];
URLEncoder.encode(parameters, "US-ASCII").replace("+", "%20");
for (int i = 1; i < paramName.length; i++)
{
parameters+= "&";
parameters += URLEncoder.encode(paramName[i], "US-ASCII").replace("+", "%20") + "=" + URLEncoder.encode(paramVal[i], "US-ASCII").replace("+", "%20");
//parameters += paramName[i] + "=" + paramVal[i];
}
}
//parameters = URLEncoder.encode(parameters, "US-ASCII");
byte[] postData = parameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL( URLstr );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setRequestProperty("charset", "US_ASCII");
conn.setRequestProperty("Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
//System.out.print(postData);
}
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
return line;
}
reader.close();
return line;
}catch(Exception e)
{
return e.getMessage();
}
}
Using UTF-8 encoding instead of US-ASCII also does not help.
What do I do?
Using UTF-8 encoding instead of US-ASCII is not just here.
//parameters = URLEncoder.encode(parameters, "US-ASCII");
byte[] postData = parameters.getBytes(StandardCharsets.UTF_8)
but all.
the below may be work.
URLEncoder.encode(parameters, "UTF-8").replace("+", "%20");
...
parameters += URLEncoder.encode(paramName[i], "UTF-8").replace("+", "%20") + "=" + URLEncoder.encode(paramVal[i], "UTF-8").replace("+", "%20");
...
conn.setRequestProperty("charset", "UTF-8");
...
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),Charsets.UTF-8));
Hope that helped

Response :java.net.SocketException: Unexpected end of file from server Java

I got this error from my program when i am call a URL from URLConnector.. the URL is
http://192.168.2.107/cgi-bin/mediaFileFind.cgi?action=findFile&object=27544704&condition.Channel=0&conditon.Dir[0]="/mnt/sd"&condition.StartTime=2014-8-1 00:00:00&condition.EndTime=2014-8-31 23:59:59
but when i capture HTTP using wire-shark then wire-shark the URl is loss
wire-shark capture only
http://192.168.2.107/cgi-bin/mediaFileFind.cgi?action=findFile&object=27544704&condition.Channel=0&conditon.Dir[0]="/mnt/sd"&condition.StartTime=2014-8-1 00:00:00
only this URL
my Java program is
public String intilizeObject(String IP, String user, String pass, String objectID, String dir, String startTime, String endTime) {
String result = "";
try {
String URL = "http://" + IP + "/cgi-bin/mediaFileFind.cgi?action=findFile&object=" + objectID + "&condition.Channel=0&conditon.Dir[0]=\"" + dir + "\"&condition.StartTime=" + startTime + "&condition.EndTime=" + endTime;
String authString = user + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(URL);
System.out.println(url);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.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);
}
result = sb.toString();
} catch (Exception e) {
result = e.toString();
}
return result;
}

when i'm trying to pass basic authentication then my code give me illegal argument exception

I have the below code
String userName = "xyz.com";
String password = "xyz.com";
URL url = new URL("http://....")
URLConnection urlConnection = url.openConnection();
String userpass = userName + ":" + password;
String basicAuth = "Basic "
+ new String(new Base64().encode(userpass.getBytes()));
System.out.println("basic auth-->" + basicAuth);
urlConnection.setRequestProperty("Authorization: ", basicAuth);
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
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 ***");
and exception is
basic auth-->Basic flkja44dsfaj=
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic aHVuZ2FtYS5jb206aHVuZ2FtYS5jb20=
at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(HttpURLConnection.java:482)
at sun.net.www.protocol.http.HttpURLConnection.isExternalMessageHeaderAllowed(HttpURLConnection.java:434)
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:2753)
at com.hungama.bbc.domObject.ContentDOMObjects.main(ContentDOMObjects.java:49)
Try this way to encode username and password:
final String userpass = userName + ":" + password;
final String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);
And you should remove ':' from field name of request property:
urlConnection.setRequestProperty("Authorization", basicAuth);

Categories