Response :java.net.SocketException: Unexpected end of file from server Java - 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;
}

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.

Servlet Exception java.io.filenotfoundexception inputstream

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();

Java proxy server fails to load the whole web page, but succeeds in loading a part of it

my Java proxy server fails to load the whole web page, but succeeds in loading a part of it.
For example, when I go to webpage, connection will time out. But if I just load one component (eg. http://www.abcde.com/abc.jpg) then it is okay.
Sorry the code is a bit long...
class ThreadPerConnect implements Runnable {
Socket clientSocket = null;
public ThreadPerConnect(Socket cs) {
clientSocket = cs;
}
public void run() {
try {
System.out.println(clientSocket.getRemoteSocketAddress());
StringBuilder sb = new StringBuilder();
// handle IO in same thread now
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
clientSocket.getOutputStream());
String request = inFromClient.readLine();
// read request from client
System.out.println(request);
sb.append(request + "\r\n");
String abc;
System.out.println("inFromClient: ");
while (!(abc = inFromClient.readLine()).isEmpty()) {
sb.append(abc + "\r\n");
System.out.println("abc is " + abc);
}
sb.append("\r\n");
String finalS = sb.toString();
System.out.println("finalS is: \n" + finalS);
// get the url
StringTokenizer st = new StringTokenizer(request);
String requestType = st.nextToken(); // skip the "GET"
String url = st.nextToken();
System.out.println("Url is " + url);
// remove "http://"
if (url.startsWith("http://"))
url = url.substring(7);
String[] parts = url.split("/", 2);
String ipRaw = parts[0];
String[] parts2 = ipRaw.split(":");
String ip = parts2[0];
int port;
if (parts2.length > 1)
port = Integer.parseInt(parts2[1]);
// get port number from request
else
port = 80;
String fileName;
if (parts.length > 1)
fileName = "/" + parts[1];
else
fileName = "/";
String httpVersion = st.nextToken();
// get the filename
System.out.printf(
"Ip is %s\t \nfileName is %s \nhttpVersion is %s", ip,
fileName, httpVersion);
// go surf actual web
Socket anotherSocket = new Socket(ip, port);
System.out.println("\ncreate anotherSocket success");
PrintWriter out = new PrintWriter(anotherSocket.getOutputStream());
DataInputStream in = new DataInputStream(
anotherSocket.getInputStream());
out.print(finalS);
out.flush();
// getting actual content
String x;
int contentLength = 0;
while (true) {
x = in.readLine();
if (x == null)
break;
if (x.isEmpty()) {
outToClient.writeBytes("\r\n");
System.out.println("END HEAD");
break;
}
outToClient.writeBytes(x + "\r\n");
System.out.println("x = " + x);
outToClient.flush();
if (x.startsWith("Content-Length:")) {
contentLength = Integer.parseInt((x.split(": "))[1]);
}
}
byte[] content = new byte[contentLength];
in.readFully(content);
outToClient.write(content, 0, contentLength);
outToClient.flush();
System.out.println("write done: " + contentLength + " bytes");
// now write back information to client
in.close();
out.close();
anotherSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Download a file from an s3 bucket with REST

I am attempting to download from an s3 bucket with REST calls. I am able to create buckets, delete buckets and list buckets. Downloading always ends with either an object not found or HTTP response code: 403. The code is below. Also does anyone know if amazon was sdk can be used with non amazon sites?
public void getObject() throws Exception
{
String fmt = "EEE, dd MMM yyyy HH:mm:ss ";
SimpleDateFormat df = new SimpleDateFormat(fmt, Locale.US);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String ob2 = "/bucket/test.txt";
String bucket = "/bucket";
String method = "GET";
String contentMD5 = "";
String contentType = "";
String date = df.format(new Date()) + "GMT";
// Generate signature
StringBuffer buf = new StringBuffer();
buf.append(method).append("\n");
buf.append(contentMD5).append("\n");
buf.append(contentType).append("\n");
buf.append(date).append("\n");
buf.append(ob2);
String signature = sign(buf.toString());
HttpURLConnection httpConn = null;
URL url = new URL("https”,”s3demo.s3demosite.com",443,bucket);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setDefaultUseCaches(false);
httpConn.setAllowUserInteraction(true);
httpConn.setRequestMethod(method);
httpConn.setRequestProperty("Date", date);
httpConn.setRequestProperty("Content-Length", "0");
String AWSAuth = "AWS " + keyId + ":" + signature;
httpConn.setRequestProperty("Authorization", AWSAuth);
// Send the HTTP PUT request.
int statusCode = httpConn.getResponseCode();
InputStream err = httpConn.getErrorStream();
InputStream is = null;
is = httpConn.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = err.read()) != -1) {
sb.append((char) ch);
}
if ((statusCode/100) != 2)
{
// Deal with S3 error stream.
InputStream in = httpConn.getErrorStream();
System.out.println("Error: "+errorStr);
}
else
{
System.out.println("download worked”);
}
}

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