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.
Related
This question might be a little bit naive...
I have written a small Java program that should query a CouchDB instance. However, CouchDB constantly returns that my user is not authorized. Using the same URL with curl works.
The Java Code:
HttpGet request = new HttpGet("http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_security");
request.addHeader("accept", "application/xml");
try {
System.out.println("Executing request " + request.getMethod() + " " + request.getUri());
ClassicHttpResponse resp = httpClient.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The response:
{"error":"unauthorized","reason":"You are not authorized to access this db."}
The curl output:
C:\Users\joche>curl -X GET http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_security
{"members":{"roles":["_admin"],"names":["ecmnp","admin"]},"admins":{"roles":["_admin"],"names":["admin"]}}
Any idea what I am doing wrong?
Using the same URL with curl works.
Your posted information does not support this claim. Your URLs are different in the two cases.
Java: _sessions
HttpGet request = new HttpGet("http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_sessions");
Curl: _security.
curl -X GET http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_security
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 ...
In the following code, EntityUtils.toString is going into IOException. When I paste 'EntityUtils.toString(entity)' on eclipse watch window, it showing me the value which is DISABLED
private String triggerRestApiCalls(String url){
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
getRequest.setHeader(
new BasicHeader("Accept", "application/json"));
try {
HttpResponse response = httpClient.execute(getRequest);
HttpEntity entity = response.getEntity();
String value = EntityUtils.toString(entity);
return value;
} catch (ClientProtocolException e) {
log.debug(e.getCause());
} catch (IOException e) {
log.debug(e.getCause());
}
log.debug("Status Unknown");
return "UNKNOWN";
}
The content value lenght is 8. The string expected is DISABLED, which is exactly of the length. The HTTP status is 200 (OK).
I used curl with same URL.
curl -i -H {Accept: application/json} http://127.0.0.1:9031/test/test.html?someDetails
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=D35C61744F4FB3A47B624FF3D0BEB026; Path=/mics/; Secure; HttpOnly
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 8
Date: Wed, 26 Nov 2014 13:23:30 GMT
DISABLED.
Any help is appreciated ! Is there any angle to encoding ?
FIRST EDIT
The Stack Trace mentions this.
java.io.IOException: Attempted read from closed stream.
The code that is executed by EntityUtils.toString()
public static String toString(
final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
I have stepped through this and there are not errors However, it closes the stream before it returns.
But the actual value that is returned is CharArrayBuffer which is not linked to the stream. The same code works in some other java file. Strange !! I am using spring.. is there a spring angle to this ?
The HttpEntity can only be read once and it seems something else is intercepting and reading the response so that when you attempt to apply EntityUtils.toString() you get this exception. I can't see why this would be happening, though you did mention there could be a Spring angle so there could be a Spring interceptor applied here.
You could try
String value = httpClient.execute(getRequest, new BasicResponseHandler());
Although from what I can see this should be fairly equivalent to the above code.
I tried uploading a file to skydrive with the rest api in java.
Here is my code:
public void UploadFile(File upfile) {
if (upload_loc == null) {
getUploadLocation();
}
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost(upload_loc + "?" + "access_token=" + access_token);
try {
MultipartEntity mpEntity = new MultipartEntity(null,"A300x",null);
ContentBody cbFile = new FileBody(upfile, "multipart/form-data");
mpEntity.addPart("file", cbFile);
post.setEntity(mpEntity);
System.out.println(post.toString());
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line2 = "";
while ((line2 = rd.readLine()) != null) {
System.out.println(line2);
}
} catch (IOException ex) {
Logger.getLogger(Onlab.class.getName()).log(Level.SEVERE, null, ex);
}
client.getConnectionManager().shutdown();
}
But when I try to run it, I get this error:
{
"error": {
"code": "request_body_invalid",
"message": "The request entity body for multipart form-data POST isn't valid. The expected format is:\u000d\u000a--[boundary]\u000d\u000aContent-Disposition: form-data; name=\"file\"; filename=\"[FileName]\"\u000d\u000aContent-Type: application/octet-stream\u000d\u000a[CR][LF]\u000d\u000a[file contents]\u000d\u000a--[boundary]--[CR][LF]"
}
}
My biggest problem is that I don't see the request itself. I couldn't find any usable toString method for that. I tried this forced boundary format, but I tried it with empty constructor too.
My file is now a txt with some text, and I think the boundary is the main problem or I should be configuring some more parameters. When I see the variables in debugging mode everything looks the same as a guide in the msdn.
I'm new in the rest world and if it possible I want to keep this apache lib with the simple to use HttpClient and HttpPost classes.
Thanks in advance, and sorry for my english.
EDIT:
Ok, after a long sleep I decided to try the PUT method instead of POST. The code work fine with minimal changes:
public void UploadFile(File upfile) {
if (upload_loc == null) {
getUploadLocation();
}
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String fname=upfile.getName();
HttpPut put= new HttpPut(upload_loc +"/"+fname+ "?" + "access_token=" + access_token);
try {
FileEntity reqEntity=new FileEntity(upfile);
put.setEntity(reqEntity);
HttpResponse response = client.execute(put);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line2 = "";
while ((line2 = rd.readLine()) != null) {
System.out.println(line2);
}
} catch (IOException ex) {
Logger.getLogger(Onlab.class.getName()).log(Level.SEVERE, null, ex);
}
client.getConnectionManager().shutdown();
}
But there is no answer for the first question yet.
Two quick things:
You should not be using the overloaded MultipartEntity constructor unless you really need to. In this case you are setting the charset to null, which is probably not a good idea. Also, your boundary delimiter is not complex enough.
Your file body content type should reflect the content of the actual file being uploaded. `multipart-formdata is normally used for HTML form data, not files. You should change this to 'text/plain', or 'image/jpeg', or whatever reflects the true mime type of the file.
Some great tools for debugging REST requests - REST Console (Chrome), REST Client (Firefox).
Some quick notes on the error message you received, it actually has quite a bit of detail. The service is expecting the following parameters to be set for the file part being sent:
name:
filename:
Content-Type: application/octet-stream
You can have the HTTP client set most of these with this code:
ContentBody cbFile = new FileBody(
upfile,
"yourFileNameHere",
"application/octet-stream",
"UTF-8");
As an assignment, I am allowed to use ServerSocket and Socket class only. Also it should be single-threaded as well.
I'm implementing a HTTP proxy server in Java, first it fetches request from client and then pushes to server, and then pushes the response back to the client.
The problem
The problem is, I have successfully get the request, send it to the end-server and get the proper HTTP response. I also can do print out the response in console. But it got stuck when I send the response to clientServer.outputstream. Firefox (requested to use, HTTP 1.0, no keep-alive requested) seems to load forever and nothing shows, and no response Firefox received from my program as well.
What I inspect when debug
Everytime a page start to load (FF request), there are always 2 client sockets. First socket contains null request, and second socket contains proper request. What I expect was that only one proper HTTP request from Firefox. Is that a weird behavior?
example:
/0:0:0:0:0:0:0:1:65194
[null request]
/0:0:0:0:0:0:0:1:65195
GET http://www.microsoft.com/ HTTP/1.0
Host: www.microsoft.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Proxy-Connection: close
Cookie: viewkey=lightweight; WT_FPC=id=269eb0e7618962f93a81347585923074:lv=1349229942007:ss=1349229580158; WT_NVR_RU=0=technet|msdn:1=:2=; omniID=c736269c_f430_4e9b_a42a_23a0c965c60a; MUID=212A1766CFE761423CD014BDCBE76158&TUID=1; MC1=GUID=08600fba7f5c5f409e67980d8a027593&HASH=ba0f&LV=20129&V=4&LU=1347643534618; A=I&I=AxUFAAAAAADGBwAA8ezRtqBBHjk3++mP1Bwj9w!!&V=4&CS=119EQ5002j10100; msdn=L=en-US
Code
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(60000);
while (true) {
clientSocket = serverSocket.accept();
[...]
// Extract request, and push to end-server
// Fetch response from end-server to client, using flush() already
// Close all input, output
// Close all sockets
} catch {[...]}
Any help is welcomed, thank you!
Full code as requested, I use PrintWriter, but before that using Byte makes no difference (not care efficiency)
import java.io.*;
import java.net.*;
import java.util.*;
public class Proxy {
static String separator = System.getProperty("line.separator");
public static void main(String args[]) {
//int port = Integer.parseInt(args[0]);
start(60000);
}
public static void start(int port) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(port);
Socket clientSocket = null;
while (true) {
clientSocket = serverSocket.accept();
System.out.println(clientSocket.getRemoteSocketAddress() + "\n" + clientSocket.getLocalSocketAddress() + "\n" + clientSocket.getInetAddress());
BufferedReader inStreamFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inLine;
Vector<String> clientRequestHeader = new Vector<String>();
String rawRequest = "";
while ((inLine = inStreamFromClient.readLine()) != null) {
if (!inLine.isEmpty()) {
clientRequestHeader.add(inLine);
rawRequest = rawRequest.concat(inLine + separator);
} else break;
}
while ((inLine = inStreamFromClient.readLine()) != null)
rawRequest = rawRequest.concat(inLine + separator);
System.out.println(rawRequest);
if (!rawRequest.isEmpty()) {
handleRequest(clientSocket, clientRequestHeader, rawRequest);
} else {
//clientSocket.close();
// Not sure how to handle null request
}
}
} catch (Exception e) {e.printStackTrace();}
}
public static void handleRequest(Socket clientSocket, Vector<String> clientRequestHeader, String rawRequest) {
HTTPRequest request = new HTTPRequest(clientRequestHeader, rawRequest);
try {
//System.out.println(rawRequest);
// Send request to end-server
Socket endServerSocket = new Socket(request.getHost(), 80);
PrintWriter outStreamToEndServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(endServerSocket.getOutputStream())));
BufferedReader stringReader = new BufferedReader(new StringReader(rawRequest));
String inLine;
while ((inLine = stringReader.readLine())!= null) {
outStreamToEndServer.println(inLine);
}
outStreamToEndServer.println();
outStreamToEndServer.flush();
// Read response header from end-server
String responseHeader = "";
BufferedReader inStreamFromEndServer = new BufferedReader(new InputStreamReader(endServerSocket.getInputStream()));
while (!(inLine = inStreamFromEndServer.readLine()).isEmpty()) {
responseHeader = responseHeader.concat(inLine + separator);
}
// Send response header to client
PrintWriter outStreamToClient = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
outStreamToClient.println(responseHeader);
outStreamToClient.flush();
// Send response body to client
String responseBody = "";
while ((inLine = inStreamFromEndServer.readLine()) != null) {
responseBody = responseBody.concat(inLine + separator);
}
outStreamToClient.println(responseBody);
outStreamToClient.flush();
endServerSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
endServerSocket.close();
//endServerSocket = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
first you should not use PrintWriter to transfer the Data, because the HTTP protocol isn't a pure text protocol the body can contain some raw data like images.
Replace your response transfer code with the code below.
InputStream in = endServerSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1)
{
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
Second point, you add always as line break the
static String separator = System.getProperty("line.separator");
This is the System specific line seperator. HTTP defines for the HTTP header and for the http header and body separation the ctrl line break charaters, so change this.
static String separator = "\r\n";
With this changes you will get your response to your browser.
Last Point you should change your client request read code also, because it will not always work if you want POST some data. Sometimes this data will transfered as raw data, by example file uploads.
Good Luck