I open a txt file on my server, get the Int and want to increment the int by 1 and write it to the file again.
I get the file with this method:
public int getCount() {
try {
URL updateURL = new URL("http://myserver.gov/text.txt");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
String tmp = new String(baf.toByteArray());
int count = Integer.valueOf(tmp);
return count;
} catch(Exception e) {
Log.e(TAG, "getAdCount Exception = " + e);
e.printStackTrace();
return -1;
}
}
now I simply increment the count and want to write it to the file.
I figured out, that it is possible to write to a file with this method:
BufferedWriter out = new BufferedWriter(new FileWriter("text.txt"));
out.write(count);
out.close();
But how I open the remote file? I dont find a way. Thanks!
##### Edit: #####
I have written this code:
URL url = new URL("http://myserver.gov/text.txt");
URLConnection con = url.openConnection();
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(count);
out.close();
But it doesnt write the count to the file.
When you want to work with URLConnection you can follow the instructions here: Reading from and Writing to a URLConnection.
Update: You will also need a running server handling POST requests to update your counter.
According to me .When you are open remote file.Firstly you have to open connection than read file content.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
than you can write file content.
Related
I'm developing a Java library for basic operations on SharePoint using Graph API.
I make a call on this entry point using SOAP UI:
https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{item-id}/content
And I obtain a raw response:
%PDF-1.6
%âãÏÓ
1751 0 obj
<</Filter/FlateDecode/First 98/Length 322/N 11/Type/ObjStm>>stream
hޜԽJ1†á[ÉL’ó“–m,md±ÁElTü)¼{3“wXYDØ©¾3!ç<)&I^kˆ!ymÁ¤gë¥ÍE ...
endstream
endobj
startxref
2993893
%%EOF
It look like i'm retrieving an input stream.
In the HttpRequest class I try to build a response object that returns the InputStream. My property fileInputStream is an InputStream:
SharePointDownloadResponseModel returnValue = new SharePointDownloadResponseModel();
InputStream inputStream = new ByteArrayInputStream(response.toString().getBytes(StandardCharsets.UTF_8));
returnValue.setFileInputStream(inputStream);
return returnValue;
Now in my manager class I try to save the input stream in the hard drive. I handle 2 cases. First case, I have a fileName a folder to store the file. My request object :
if(request.getDownloadFolder() != null && request.getFileName() !=null) {
InputStream initialStream = returnValue.getFileInputStream();
FileOutputStream fos = new FileOutputStream(request.getDownloadFolder() + "/" + request.getFileName());
BufferedOutputStream bos = new BufferedOutputStream(fos );
// Read bytes from URL to the local file
byte[] buffer = new byte[4096];
int bytesRead = 0;
System.out.println("Downloading " + request.getFileName());
while ((bytesRead = initialStream.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
// Close destination stream
bos.close();
// Close URL stream
initialStream.close();
}
The document is created where it should be created but the file is damaged and can't be opened. I wonder what is the issue at this stage.
I finally solved my issue. Here is a basic method that shows my implementation :
public class DownloadFile {
public static void main(String[] args) throws IOException {
String url = "https://graph.microsoft.com/v1.0/drives/{driveId}/items/{itemId}/content";
SharePointCredentialRequest sharePointCredentialRequest = new SharePointCredentialRequest(Constants.TENANT_CLIENT_ID,
Constants.TENANT_CLIENT_SECRET, Constants.TENANT_AUTHORITY);
String token = Utils.getToken(sharePointCredentialRequest);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", "Bearer " + token);
try (CloseableHttpResponse response = client.execute(httpGet)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(response.getAllHeaders().length);
System.out.println(entity.getContentEncoding());
System.out.println(entity.getContentLength());
System.out.println(entity.getContentType().getElements().toString());
try {
// do something useful with the stream
InputStream inputStream = IOUtils.toBufferedInputStream(response.getEntity().getContent());
File targetFile = new File("C:\\myFolder\\kant.pdf");
FileUtils.copyInputStreamToFile(inputStream, targetFile);
} catch (IOException | UnsupportedOperationException e) {
e.printStackTrace();
}
}
}
}
}
I always understood that in order to read a file on the server you have to download it first ie:
URL url = new URL(myUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
input = connection.getInputStream();
output = new FileOutputStream(TEMP_FILE_PATH);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
output.write(data, 0, count);
}
Is my assumption incorrect? Can you read / parse a file without downloading it?
Is it possible to parse a file ON server?
Yes, if your parser is running on the server. If your parser isn't running with direct access to the file then you have to fetch the file somehow to parse it.
Is it possible to parse a file ON server?
Definitely YES you can.
Based on your code snippet, you seem to want to read and parse a file content from a remote server or http request.
I have an application in which user can preview a file from a remote file server.
If you can access a file using "myUrl" directly, you can also read and parse the file in java.
Please try to use the code snippet below.
You may need to include org.apache.http.client.HttpClient library.
HTTP GET Example
String myUrl = "http://enter.the.url.you.want";
OutputStream output = new FileOutputStream("TEMP_FILE_PATH");
// Define Header information if you want to have.
Map<String, String> headers = new HashMap<String, String>();
headers.put("range", "bytes=0-51199");
// org.apache.http.client.HttpClient
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(myUrl);
if(headers != null){
Iterator<String> iter = headers.keySet().iterator();
while(iter.hasNext()){
String key = (String)iter.next();
get.addHeader(key, headers.get(key));
}
}
HttpResponse res = client.execute(get);
InputStream input = res.getEntity().getContent();
int count = 0;
byte[] data = new byte[4096];
StringBuilder sb = new StringBuilder();
while ((count = input.read(data)) != -1) {
sb.append(new String(data, 0, count, "UTF-8"));
// Here is the place you can read a file.
output.write(data);
}
input.close();
output.close();
HTTP POST Example
String myUrl = "http://enter.the.url.you.want";
OutputStream output = new FileOutputStream("TEMP_FILE_PATH");
// Define parameters if you want to have.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "some-value"));
// Define Header information if you want to have.
Map<String, String> headers = new HashMap<String, String>();
headers.put("range", "bytes=0-51199");
// org.apache.http.client.HttpClient
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(myUrl);
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
if(headers != null){
Iterator<String> iter = headers.keySet().iterator();
while(iter.hasNext()){
String key = (String)iter.next();
post.addHeader(key, headers.get(key));
}
}
HttpResponse res = client.execute(post);
InputStream input = res.getEntity().getContent();
int count = 0;
byte[] data = new byte[4096];
StringBuilder sb = new StringBuilder();
while ((count = input.read(data)) != -1) {
sb.append(new String(data, 0, count, "UTF-8"));
// Here is the place you can read a file.
output.write(data);
}
input.close();
output.close();
I have an app running on J2ME that needs to access the Instagram API. Specifically, I need to post a comment. This is a Post method. So I try to add the "text" parameter to the body of the request by using HttpConnection.setRequestProperty(), but this doesn't seem to work, as Instagram doesn't recognize that the parameter is present. I think this method is failing to write the parameter to the body of the Http request. Any idea how I can make this work in j2me?
Here's my code:
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] response = null;
HttpConnection connection = null;
String url = "";
try {
url = "https://api.instagram.com/v1/media/" + mediaId + "/comments?access_token="+InstagramAPIUtil.accessTokenTest;// POST
url = Util.urlEncodeSpaces(url);
System.out.println(url);
connection = (HttpConnection)Connector.open(url,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("text", comment);
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
is = connection.openInputStream();
if (is != null) {
int ch = -1;
while ((ch = is.read()) != -1) {
bos.write(ch);
}
response = bos.toByteArray();
}
System.out.println("response: "+new String(response));
System.out.println("request: "+connection.getRequestProperty("text"));
return true;
}
And here's what I'm getting back from Instagram:
{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"Missing 'text'"}}
I have not much experience in the HTTP area, but I think you need to write to the output stream that you can get from connection. I don't see where in your code you send actual data.
HttpURLConnection c = (HttpURLConnection) new URL("").openConnection();
OutputStream out = c.getOutputStream();
InputStream in = c.getInputStream();
How do I retrieve the contents of a file and assign it to a string?
The file is located on a https server and the content is plain text.
I suggest Apache HttpClient: easy, clean code and it handles the character encoding sent by the server -- something that java.net.URL/java.net.URLConnection force you to handle yourself:
String url = "http://example.com/file.txt";
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(url));
String contents = EntityUtils.toString(response.getEntity());
Look at the URL Class in the Java API.
Pretty sure all you need is there.
First download the file from the server using the URL class of java.
String url = "http://url";
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("file.txt");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
bout.write(data);
}
bout.close();
in.close();
Then read the downloaded file using FileInputStream class of java
File file = new File("file.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(strContent.toString());
Best answer I found:
public static String readPage(String url, String delimeter)
{
try
{
URL URL = new URL(url);
URLConnection connection = URL.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, lines = "";
while ((line = reader.readLine()) != null)
{
if(lines != "")
{
lines += delimeter;
}
lines += line;
}
return lines;
}
catch (Exception e)
{
return null;
}
}
This is the method I have in my java application. It is reading the bytes correctly, I have logged to see if it was. The problem is that the php is not realizing the data is there. I have tested and the .php reads that $_POST is set, but is empty.
public void screenshot(BufferedImage screenshot) {
try {
ImageIO.write(screenshot, "png",
new File(Environment.getStorageDirectory().toString()
.concat(File.separator + SCRIPT_NAME + ".png")));
HttpURLConnection httpUrlConnection;
OutputStream outputStream;
BufferedInputStream fileInputStream;
BufferedReader serverReader;
int totalBytes;
String response = "";
String serverResponse = "";
String localFileName = Environment.getStorageDirectory().toString()
.concat(File.separator + SCRIPT_NAME + ".png");
// Establish a connection
httpUrlConnection = (HttpURLConnection) new URL(
"http://www.scripted.it/scriptoptions/utils/saveScreenshot.php?user="
+ SupraCrafter.statHandler.getUser())
.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
outputStream = httpUrlConnection.getOutputStream();
// Buffered input stream
fileInputStream = new BufferedInputStream(new FileInputStream(
localFileName));
// Get the size of the image
totalBytes = fileInputStream.available();
// Loop through the files data
for (int i = 0; i < totalBytes; i++) {
// Write the data to the output stream
outputStream.write(fileInputStream.read());
}
// Close the output stream
outputStream.close();
// New reader to get server response
serverReader = new BufferedReader(new InputStreamReader(
httpUrlConnection.getInputStream()));
// Read the servers response
serverResponse = "";
while ((response = serverReader.readLine()) != null) {
serverResponse = serverResponse + response;
}
System.out.println(serverResponse);
// Close the buffered reader
serverReader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
URL url = new URL(
"http://scripted.it/scriptoptions/utils/setScreenshotStatus.php?user="
+ SupraCrafter.statHandler.getUser() + "&pass="
+ SupraCrafter.statHandler.getPass() + "&script="
+ SCRIPT_NAME + "&status=1");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
Here is the .php file:
<?
// Config
$uploadBase = "../screenshots/";
$uploadFilename = $_GET['user'] . ".png";
$uploadPath = $uploadBase . $uploadFilename;
// Upload directory
if(!is_dir($uploadBase))
mkdir($uploadBase);
// Grab the data
$incomingData = file_get_contents('php://input');
// Valid data?
if(!$incomingData)
die("No input data");
// Write to disk
$fh = fopen($uploadPath, 'w') or die("Error opening file");
fwrite($fh, $incomingData) or die("Error writing to file");
fclose($fh) or die("Error closing file");
echo "Success";
?>
It always echos 'no input data.'
You are not encoding the content with application/x-www-form-urlencoded. You should not simply copy the bytes into the HTTP payload, but instead encode it correctly.
application/x-www-form-urlencoded is not the only possible way of encoding it, multipart/form-data is another common choice. Both are supported by almost all webservers, and as a consequence by PHP.
A tutorial on how to encode using Java is here : http://www.devx.com/Java/Article/17679
Why don't you use Apache's HttpClient or similar library that already do that tedious work for you?
Apache HttpClient : http://hc.apache.org/httpcomponents-client-ga/