XML body of HTML response is "0"? - java

I am trying to send an HTTP request in order to get a response (TCP-IP) , which should contain XML . Here is the method I am using for sending a request and returning it :
public String getResponse() throws IOException {
String result="";
Socket socket = new Socket(host,port);
//encoding login and password
String username = "root";
String password = "ut72";
String auth = username + ":" + password;
String encodedAuth = Base64.encode(auth.getBytes());
//sending request
PrintWriter request = new PrintWriter( socket.getOutputStream() );
request.print( "GET " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Authorization: Basic " + encodedAuth + "\r\n" +
"Connection: close\r\n\r\n");
request.flush( );
//waiting for response
InputStream inStream = socket.getInputStream( );
BufferedReader rd = new BufferedReader(
new InputStreamReader(inStream));
String line;
while ((line = rd.readLine()) != null) {
result = result+"\n"+line;
}
return result;
}
Here is my main :
public static void main(String[] args) throws URISyntaxException, IOException {
GetDataFromUnidrive getter = new GetDataFromUnidrive("http://192.168.130.182/US/4.02/dynamic/readparval.xml");
String response = getter.getResponse();
System.out.println(response);
Here is the response I get :
HTTP/1.1 200 OK
Content-Type: text/xml
Cache-Control: private
Expires: Thu, 26 Oct 1995 00:00:00 GMT
Transfer-Encoding: chunked
Server: Allegro-Software-RomPager/4.01
Connection: close
0
Process finished with exit code 0
If I am guessing right, the "0" in the middle is the XML response . But ... this is NOT what I should get ; indeed, If I am typing my request in a browser, typing "http://192.168.130.182/US/4.02/dynamic/readparval.xml", I am getting this (this what I want to obtain with my program) :
Can somebody explain me reasons which could make this "0" appear ?
EDIT : Here is what I am doing with HttpClient (the same things seem to occur)
String url = "http://192.168.130.182/US/4.02/dynamic/readparval.xml";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String result = "";
String line = "";
while ((line = rd.readLine()) != null) {
result+=line;
}
return result;
This gives me the result :
Response Code : 200
Process finished with exit code 0
When I am trying to have more information...(I'm doing String result = response.getEntity().toString();) I am getting this :
Response Code : 200
ResponseEntityProxy{[Content-Type: text/xml,Chunked: true]}
Process finished with exit code 0
So I guess I am still getting the chuncked tranfert-enconding anyway ...

Related

I want to create a user on Google Duo through Java Rest api. Followed documentation but getting error

I am creating a Java Rest api to create users on Google Duo admin. I am following the documentation https://duo.com/docs/adminapi and I have added auth and date/time header but still I am getting unauthorised error 401. Can anyone guide me what am I doing wrong I have read the doc and added all the mandatory headers.
public static void POSTRequest() throws IOException {
String userCredentials = "Username:Password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
URL obj = new URL("https://api-e9770554.duosecurity.com");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
Error:
{
"code": 40101,
"message": "Missing request credentials",
"stat": "FAIL"
}
Response code: 401 (Unauthorized); Time: 2022ms; Content length: 73 bytes

get MailChimp response with Java

I want to use the MailChimp api to add a subscriber. As a start, want to read from one of the REST I'm trying to get a response back from the MailChimp api.
I seem to be doing the authorization correctly as I'm getting status 200, but for some reason, I am not getting the response.
Here is the code so far:
public void doPostAction() throws IOException{
// BASIC Authentication
String name = "user";
String password = apikey;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = httpConnection.getInputStream();
// check status
System.out.println("DoPost: status: " + httpConnection.getResponseCode());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println("DoPost response: \n" + line);
br.close();
}
Looking at the MailChimp playground, it seems like I'm missing out on a lot...
How do I get the response?
****/ EDIT /****
If anyone's looking at the above code, the output should be:
System.out.println("DoPost response: \n" + sb); // not line
OK, the above code works. Basic error.
I was examining the line variable when it was null, not the response...
When I change to:
System.out.println("DoPost response: \n" + line); // not line
System.out.println("DoPost response: \n" + sb); // but sb StringBuilder
...it works.

getting a invalid_request_body error when i try to void a document

When trying to void a in-progress document, I received the invalid_request_body error(The request body is missing or improperly formatted. Data at the root level is invalid). Is there something missing on the request body ?
url = baseURL + "/envelopes/" + envelopeId;
body = "";
// re-use connection object for second request...
conn = InitializeRequest(url, "PUT", body, authenticationHeader);
String requestBody = "\r\n\r\n--BOUNDARY\r\n" +
"Accept: application/xml" +
"Content-Type: application/xml\r\n" +
"\r\n" +
body + "\r\n\r\n--BOUNDARY\r\n" +
"status: voided\r\n" +
"voidedReason: Time-out\r\n" +
"\r\n";
String reqBody2 = "\r\n" + "--BOUNDARY--\r\n\r\n";
DataOutputStream dos= new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(requestBody.toString());
//dos.write(bytes);
dos.writeBytes(reqBody2.toString());
dos.flush();
dos.close();
System.out.println("STEP 2: Retrieving envelope information for envelope " + envelopeId + ".\n");
status = conn.getResponseCode(); // triggers the request
if( status != 200 ) { // 200 = OK
System.out.println(conn);
System.out.println(status);
errorParse(conn, status);
throw new RuntimeException();
}
// display results
response = getResponseBody(conn);
Following up with your comments for the benefit of the community...
This is the request body that worked for you in the end:
request body## String requestBody = "<envelope>" + "<status>voided</status>" + "<voidedReason>user aborted</voidedReason>" + "</envelope>"

PHP script not found by Java but works in browser

I have several PHP sripts saved in my /var/www/ directory. I can run them from my browser but Java can't see them.
Here is output from browser:
And from Java:
DB: Error executing script: get_profile_ids
HTTP/1.1 404 Not Found [Date: Tue, 16 Apr 2013 11:52:40 GMT, Server: Apache/2.2.22 (Ubuntu), Vary: Accept-Encoding, Content-Length: 288, Keep-Alive: timeout=5, max=100, Connection: Keep-Alive, Content-Type: text/html; charset=iso-8859-1]
DB: Result:
My Java code:
public class ServerTest {
public static void main(String [] args) {
callPHPScript("get_print_profile_ids", new ArrayList<NameValuePair>());
}
public static String callPHPScript(String scriptName, List<NameValuePair> parameters) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/" + scriptName);
String line = "";
StringBuilder stringBuilder = new StringBuilder();
try {
post.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != 200)
{
System.out.println("DB: Error executing script: " + scriptName);
System.out.println(response.toString());
}
else {
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DB: Result: " + stringBuilder.toString());
return stringBuilder.toString();
}
}
And my PHP Script:
<?php
include('connect_db.php');
include('tools.php');
$query = 'SELECT id FROM fingerprint_profiles';
$result = mysql_query($query);
echo($result);
?>
Does anybody know why this might happen??
You are missing the .php, change:
HttpPost post = new HttpPost("http://localhost/" + scriptName);
to
HttpPost post = new HttpPost("http://localhost/" + scriptName + ".php");
here's the hint:
System.out.println("DB: Error executing script: " + scriptName);
is logging
DB: Error executing script: get_profile_ids
change your test call to
callPHPScript("get_profile_ids.php", new ArrayList<NameValuePair>());
and you'll likely get a successful result.
Your Java code calls get_profile_ids while your browser screenshot shows get_profile_ids.php. Change your Java code to call get_profile_ids.php as well.

Http client 408 status code

I am working on building my own http client. I got it working but tried to clean up the code and make it more efficient. No syntax errors or run time errors. However for some reason when I run the program it hangs when it tries to send the first GET request and ends up timing out with this message:
408 Request Time-out: Server timeout waiting for the HTTP request from the client.
This is my entire class.
public class MyHttpClient {
//Variables
String host;//Host name
int port; //port number to connect to
String path; //Path of resource being requested
String method; //Type of method (GET or POST)
String blankLine = "\r\n"; //Carriage return
String line; //Hold Strings returned from server
int status; //Hold the response code
String description; //Hold the response code description
String name; //Hold name of NameValuePair
String value;//Hold value of NameValuePair
String body; //Hold the body of the response
String queryString;//Hold the query string of the request
int length; //Hold the content length being sent to server
public MyHttpResponse execute(MyHttpRequest request) throws IOException {
//Create the Http response object
MyHttpResponse response = new MyHttpResponse();
//Establish a connection to the server
//Get host and port
host = request.getHost();
port = request.getPort();
Socket connectionSocket = new Socket(host,port);
//Create I/O streams
//input
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//output
DataOutputStream outToServer = new DataOutputStream(connectionSocket.getOutputStream());
//Get the file path
path = request.getPath();
//Get the type of method
method = request.getMethod();
//Handle GET request
if(method.equalsIgnoreCase("GET")){
System.out.println(host + " " + port + " " + path);
//REQUEST
//Construct the GET request and send to server via output stream
outToServer.writeBytes("GET " + path + " HTTP/1.0" + "\r\n"); //Request line
outToServer.writeBytes("Host: localhost.com" + "\r\n"); //GET request headers
outToServer.flush();
//RESPONSE
//Read in the response from the server
line = inFromServer.readLine();
//Check the status code & assign to response - if not 200 throw error!
status = Integer.parseInt(line.substring(9,12));
response.setStatus(status);
//Get the status code description & assign to response - if 200 should be OK.
description = line.substring(13);
response.setDescription(description);
//Get the response headers
do{
line = inFromServer.readLine();
if(line != null){
name = line.substring(0, line.indexOf(":"));//Key
value = line.substring(line.indexOf(":"));//Value
response.addHeader(name, value);//Add to response object
}
}while(line != null && line.length() == 0);
//Do the above loop until a blank line is reached. This indicates
//the end of the headers and the start of the content.
//Get the body (content) - After a blank line
StringBuilder sb = new StringBuilder();
do{
line = inFromServer.readLine();
if(line != null){
sb.append(line).append("\n");
}
}while(line != null);
//Loop until there is no more lines left.
//Convert the data to a string and set it as the response object's body.
body = sb.toString();
response.setBody(body);
}
//Handle POST request
if(method.equalsIgnoreCase("POST")){
//REQUEST
//Get the query string from request and it's length
queryString = request.getQueryString();
length = queryString.length();
//Construct the POST request and send to the server via the output stream
outToServer.writeBytes("POST: " + path + " HTTP/1.0" + blankLine);//Request line
outToServer.writeBytes("Host: localhost.com" + blankLine);//Header lines
outToServer.writeBytes("Content-Type: application/x-www-form-urlencoded" + blankLine);
outToServer.writeBytes("Content-Length: " + String.valueOf(length) + blankLine);
outToServer.writeBytes(blankLine); //blank line to indicate end of headers and start of body
outToServer.writeBytes(queryString);//query string "hidden" in POST request body, in GET this query string is "visible",added to the url.
outToServer.flush();
//RESPONSE
//read the response and get the status code and assign to the response
line = inFromServer.readLine();
status = Integer.parseInt(line.substring(9,12));
response.setStatus(status);
//get the response status description and assign to response
description = line.substring(13);
response.setDescription(description);
//read the response headers
do{
line = inFromServer.readLine();
if(line != null){
name = line.substring(0, line.indexOf(":"));
value = line.substring(line.indexOf(":"));
response.addHeader(name, value);
}
}while(line != null && line.length() == 0);
//(above)Same as GET - loop through the headers until blank line reached
//indicating the start of the response body.
//read the response body (content)
StringBuilder sb = new StringBuilder();
do{
line = inFromServer.readLine();
if(line != null){
sb.append(line).append("\n");
}
}while(line != null && line.length() == 0);
//(above)Loop through until there is a blank line - end of the content
//Convert to string and assign as response body.
body = sb.toString();
response.setBody(body);
}
//Close the connection to the server
connectionSocket.close();
//Return the response
return response;
}
}//END OF CLASS
Can anyone see what might be causing it? The one thing I changed from my original working code was the output stream from:
s.getOutputStream().write(("GET " + path + " HTTP/1.0\r\n").getBytes("ASCII"));
to use a DataOutputStream
outToServer.writeBytes("GET " + path + " HTTP/1.0" + "\r\n");
As soon as I posted the question I realised my error. I forgot to put a blank line after the GET request headers.
This fixed it:
//Construct the GET request and send to server via output stream
outToServer.writeBytes("GET " + path + " HTTP/1.0" + "\r\n"); //Request line
outToServer.writeBytes("Host: localhost.com" + "\r\n"); //GET request headers
outToServer.writeBytes(blankLine);
outToServer.flush();

Categories