how to read http get response (restful-ws) as java.io.file - java

File file = new File("C:\\testing.txt")
Can we achieve by any means somthing like:
File file = new File("https://stackoverflow.com/ws-server/lookup/1.0/1234")
The below webservice returns me the same file content as txt in string form.
https://stackoverflow.com/ws-server/lookup/1.0/1234
Can anyone please let me know if its doable.

You can write the response to a File.
Look at this answer for details.
After this you can just open the File as you are used to.

Is this a convenient implementation? NOTE: it uses Apache HttpComponents Client and Apache Commons IO
public class RunApp {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<File> responseHandler = new ResponseHandler<File>() {
public File handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
File file = new File("Desired-filename");
IOUtils.copy(entity.getContent(), new FileOutputStream(file));
return file;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
File file = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(file.getAbsolutePath());
} finally {
httpclient.close();
}
}
}

An even shorter solution would be to use FileUtils.copyURLToFile(URL, File) from Apache Commons IO

Related

Upload File from GWT to another domain , response is always null

I am uploading a File from GWT to a different domain
File Uploads well , But the response i sent from the server always reaches as "null" at the client side
response.setContentType("text/html");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().print("TEST");
response is NULL only when i upload the file on a different domain ... (on same domain all is OK)
I also see this in GWT documentation
Tip:
The result html can be null as a result of submitting a form to a different domain.
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FormPanel.SubmitCompleteEvent.html
Is there any way I can receive back a response at my client side when i am uploading file to a different domain
There are 2 possible answer:
Use JSONP Builder
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.requestObject(url, new AsyncCallback<FbUser>() {
#Override
public void onFailure(Throwable ex) {
throw SOMETHING_EXCEPTION(ex);
}
#Override
public void onSuccess(ResponseModel resp) {
if (resp.isError()) {
// on response error on something
log.error(resp.getError().getMessage())
log.error(resp.getError().getCode())
}
log.info(resp.getAnyData())
}
Not to use GWT to upload, rather use other client like apache HttpClient
public uploadFile() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
FileBody bin = new FileBody(new File(UPLOADED_FILE));
long size = bin.getContentLength();
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("PART", bin);
String content = "-";
try {
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity ent = response.getEntity();
InputStream st = ent.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(st, writer);
content = writer.toString();
} catch (IOException e) {
return "false";
}
return content;
}
Hope it helps

rest api to download a file returns contents of file as a response without downloading it

#GET
#Path("/{loginId}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadExportedFile(#PathParam("loginId") String loginId) {
File file = new File("D://abc.txt");
Response.ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=newfile.txt");
response.type(MediaType.APPLICATION_OCTET_STREAM_TYPE);
return response.build();
}
This gives response as a content of file and not downloading it
Monika if you use spring I recommend return response entity resource with headers something like this
#GetMapping("/api/config)
fun config(#PathVariable id: String): ResponseEntity<Resource> {
val config = someService.getConfig(hotelId = id)
val resource InputStreamResource(objectMapper.writeValueAsString(config)
.byteInputStream(Charsets.UTF_8))
val responseHeaders = HttpHeaders()
responseHeaders.add("content-disposition",
"attachment;filename=config.json")
responseHeaders.add("Content-Type",MediaType.APPLICATION_OCTET_STREAM_VALUE)
return ResponseEntity.ok()
.headers(responseHeaders)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource)
}
Here you have some other answer about
Content-Disposition and Content Type
The frontend should not have an impact on downloading file.
Your code here is the API you are implementing and it returns the content of the file. Downloading your file should be done from a client by generating a new file after you get the content. For instance, with the HttpClient lib, you will get this code:
CloseableHttpClient client;
HttpGet request;
HttpResponse response;
HttpEntity entity;
try {
client = HttpClientBuilder.create().build();
request = new HttpGet(URI);
response = client.execute(request);
entity = response.getEntity();
// The file not found, or is not available
if(response.getStatusLine().getStatusCode() == 404) {
throw new CustomException("The URI is not valid");
} else {
InputStream is = entity.getContent();
try (FileOutputStream fos = new FileOutputStream(new File(newFilePath))) {
int inByte;
while((inByte = is.read()) != -1) {
fos.write(inByte);
}
}
is.close();
client.close();
}
} catch(IOException e) {
e.printStackTrace();
}
If you want the file to be directly downloaded when you call the URL, you have to give the complete path with the name of the file : http://yourhost/yourfile.txt, and of course the file should be available on the server. Behind this URL, it is just a href HTML tag, that will point on your file. In your API, your URL will looks something like this : #Path("/{loginId}/{file}"), where {file} stands for the file you want to download.

authentication with Java and apache HttpClient 4.5.1

my problem is, that i don't get, how to log in with Java and Apache HttpComponents (HttpClient v4.5.1) into a specific site: Site im trying to log in. I have the username (test_admin) and the password (testing) to log in but i think this is not enough and i need something more. I think this has something to do with the field security_token i see when i make a get request to the uri, but i dont know how to keep that or how to save that and what to do with it afterwards. There is also a hidden input field with the name login-ticket, but i dont know what's that for either. I want to login, because i need to see the courses and add some new ones. After trying with several code implementations im stick with this code:
public static void setGet(CloseableHttpClient httpClient) throws UnsupportedOperationException, IOException
{
HttpGet httpGet = new HttpGet("http://demo.studip.de/dispatch.php/admin/courses");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("GET Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
showEntity(httpResponse,httpResponse.getEntity());
}
public static HttpEntity setParam(int count, String[] params, String[] values)
{
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (int i = 0; i < count; i++)
{
formparams.add(new BasicNameValuePair(params[i],values[i]));
System.out.println("Paramater------------------> "+params[i]+" Values-------------> "+values[i]);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
return entity;
}
public static void setPost(HttpClient httpC) throws ClientProtocolException, IOException
{
HttpPost httppost = new HttpPost("http://demo.studip.de/dispatch.php/admin/courses");
//String[] params = {"loginname", "password"};
//String[] values = {"test_admin", "testing"};
//HttpEntity entity = setParam(2, params, values );
HttpResponse response = httpC.execute(httppost);
System.out.println("POST Response Status:: "
+ response.getStatusLine().getStatusCode());
showEntity(response, response.getEntity());
}
public static void showEntity(HttpResponse httpResp, HttpEntity httpClient) throws IOException
{
httpClient = httpResp.getEntity();
if (httpClient != null)
httpClient = new BufferedHttpEntity(httpClient);
System.out.print(EntityUtils.toString(httpClient));
}
public static void main(String[] args) throws InterruptedException, IOException {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test_admin", "testing"));
CloseableHttpClient hc =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
setGet(hc);
// HttpClient httpclient = HttpClients.createDefault();
setPost(hc);
setGet(hc);
}
The problem now ist that i get everytime the same answer from the server i only see the login page in the response, where the server asks me to login with username and password.
Which code you get from the server 401,403,301,302 or 200?

REST PUT with external file JSON to httpClient Java?

I need to translate this for example :
curl -X PUT -u ident:pass -H "Content-Type : application/json" --data-binary #G:\jonJob.json "http://localhost:8080/jobs/"
(this works).
in java with httpClient. I have try a lot of things but nothing work..
Someone could help me please ?
What I've tried :
public class PostFile {
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ident", "pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPut httppost = new HttpPut("http://localhost:8080/jobs/");
File file = new File("G:/jsonJob.json");
HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.create("application/json"), file.getName()).build();
httppost.setEntity(httpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
}
}
Result : "HTTP/1.1 415 Not supported type" (unsupported media type)
for your http req headers -H you have java runnable imple with interceptor:
public void run() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(YourConnectionMgr.getInstance())
.addInterceptorLast(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (request.getRequestLine().getMethod() == "POST"){
request.addHeader("Content-Type", "application/json") ;
see examples here to figure out 'connectionManager'
for simple auth, add this
to map in memory and POST a file see answer here
Note, you will eventually want some kind of async http client for java , you can google for that. The apache examples like in the link provided are mostly blocking network calls AFAIK

SpringMVC-FileUpload - The request sent by the client was syntactically incorrect

I've seen couple of qts on the same topic. But I didn't find any clue of this error.
I am working on a POC and following the link below.
http://spring.io/guides/gs/uploading-files/
As mentioned in the above tutorial, in standalone mode[spring embeded Tomcat] it is working absolutely fine.
But I want to deploy it as webapplication. So, I have created a separate SpringMVC project and added the following controller.
Controller file
#Controller
public class FileUploadController {
#RequestMapping(value="/upload", method=RequestMethod.GET)
public #ResponseBody String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
}
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
}
I've written the following client ( As I don't want to use RestTemplate here).
Service Client
private static final String URL_GET = "http://localhost:8080/SpringMVC/upload";
static String URL = "http://localhost:8080/SpringMVC/upload";
public static void main(String[] args) throws Exception {
PropertyConfigurator.configure("C:/DevEnvProject/eclipse/workspace_exp/OCR/log4j.properties");
testGet();
testPOST();
}
private static void testGet() throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(URL_GET);
HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
}
static void testPOST() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("name", new StringBody("testIcon.png"));
entity.addPart("file", new FileBody(new File("C:/testIcon.png")));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
}
I couldn't make a successful call to the POST endpoint. Everytime, I'm getting the following exception.
400 Bad Request - The request sent by the client was syntactically incorrect
'GET' call is working fine. I compared the the log of the 'POST' request with the same 'POST' request which I got while testing with standalone approach as mentioned in the spring tutorial. Didn't find any diff in the request part.
I know that I'm quite verbose in this post. I wanted to give as much context info as possible. Please help.
Thanks
There are 2 things you need to do:
First, add the Apache Commons FileUpload library to your class path. If you use maven, you can get the dependency here. If you don't, you can still download the jar and add it manually.
Second, you have to declare a MultipartResolver bean in your context with name multipartResolver. With Apache Commonds FileUpload, you can use CommonsMultipartResolver. For example, with Java config, that would be
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
// set any fields
return commonsMultipartResolver;
}
With XML config,
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set any properties -->
</bean>
This is further documented in the Spring official documentation.

Categories