How to download a file from another GET call using Apache Http? - java

I'm trying to download a file from my local Jasper server using REST API:
http: // : / jasperserver [-pro] / rest_v2 /
reportExecutions / requestID / exports / exportID / outputResource
My interest is that I want to prevent my client from saving a file on the server, I want a direct download using the output from the previous GET call (as a small bridge, nothing more).
I have been using the Apache Http API to do this. Previously I had to make other calls to authenticate, to request the resource and now .... download it.
My problem is that when I download the file, it comes with 0kb and the browser reports that the file is corrupted (it is a pdf that I want to download).
This is the code I'm using to download the file.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String fileType = "pdf"; // request.getParameter("type") pdf o xls
CloseableHttpClient httpClient = HttpClients.createDefault();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("j_username",username));
urlParameters.add(new BasicNameValuePair("j_password",pass));
boolean valid = executeAuthenticationValidation(urlParameters,response,httpClient,httpContext);
if(valid) {
ReportObject repObj = requestJasperReport(request.getParameter("params"),fileType,response,httpClient,httpContext);
if(repObj != null) {
String requestId = repObj.requestId;
String exportId = repObj.exports.get(0).id;
HttpGet get = new HttpGet("http://localhost:8081/jasperserver/rest_v2/reportExecutions/"+requestId+"/exports/"+exportId+"/outputResource");
int rescod;
HttpEntity content;
String name;
String filetype;
try (CloseableHttpResponse chres = httpClient.execute(get,httpContext);) {
StatusLine status = chres.getStatusLine();
rescod = status.getStatusCode();
name = chres.getFirstHeader("Content-Disposition").getValue().split(";")[1];
filetype = chres.getFirstHeader("Content-Type").getValue();
content = chres.getEntity();
}
if(rescod==200) {
response.setContentType(filetype);
response.setHeader("Content-disposition", name);
try (InputStream in = content.getContent();
OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
}
httpClient.close();
}
}
} else {
// Error
}
}

Ok, Lol my bad, this happens when you don't control properly the Try-catch with Resources. Just had to move some code inside of the Try block:
if(repObj != null) {
String requestId = repObj.requestId;
String exportId = repObj.exports.get(0).id;
HttpGet get = new HttpGet("http://localhost:8081/jasperserver/rest_v2/reportExecutions/"+requestId+"/exports/"+exportId+"/outputResource");
HttpEntity content;
String name;
String filetype;
try (CloseableHttpResponse chres = httpClient.execute(get,httpContext);) {
StatusLine status = chres.getStatusLine();
name = chres.getFirstHeader("Content-Disposition").getValue().split(";")[1];
filetype = chres.getFirstHeader("Content-Type").getValue();
content = chres.getEntity();
if(status.getStatusCode()==200) {
response.setContentType(filetype);
response.setHeader("Content-disposition", name);
response.setHeader("Content-Length", String.valueOf(content.getContentLength()));
try (InputStream in = content.getContent();
OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
}
httpClient.close();
}
}
}
} else {
// Error
}
I was getting 0kb because the InputStream was closing it early.

Related

I want to download a file from the frontend, need to send input stream to the frontend. Using download link to download file from backend

The code below uses a protected url ,username password to get the files to download. I can only manage to download the file in the springboot folder. I want to send the file data to the frontend to have it download there to your downloads.
I might be wrong but I need to send the inputstream to the frontend, then download that data to a file? Any suggestions as to what I am doing wrong when trying to send this data to the frontend.
#RequestMapping(value = "/checkIfProtectedOrPublic/", method = RequestMethod.POST)
public ResponseEntity checkIfProtectedOrPublic(#RequestPart("prm_main") #Valid CheckProtectedData checkProtectedData) throws IOException {
List<PrmMain> prmMainList = prmMainRepository.findAllByCode("PROTECTED_LOGIN");
boolean success = true;
InputStream in = null;
FileOutputStream out = null;
for (int i = 0; i < prmMainList.size(); i++) {
if (prmMainList.get(i).getData().get("email").equals(checkProtectedData.getEmail())) {
String username= (String) prmMainList.get(i).getData().get("email");
String password= (String) prmMainList.get(i).getData().get("password");
try{
URL myUrl = new URL(checkProtectedData.getDownloadLink());
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestMethod("GET");
String userCredentials = username.trim() + ":" + password.trim();
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
in = conn.getInputStream();
out = new FileOutputStream(checkProtectedData.getFileName());
int c;
byte[] b = new byte[1024];
while ((c = in.read(b)) != -1){
out.write(b, 0, c);
}
}
catch (Exception ex) {
success = false;
}
finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
}
if (out != null)
try {
out.close();
} catch (IOException e) {
}
}
}
}
return ResponseEntity.of(null);
}
//Complete redo of the code
PrmMain loginParameter = prmMainRepository.findAllByCode("PROTECTED_LOGIN").get(0);
if (loginParameter == null)
throw new IllegalArgumentException("Protected Login Not Configured");
// now try and download the file to a byte array using commons - this bypasses CORS requirements
HttpGet request = new HttpGet(checkProtectedData.getDownloadLink());
String login = String.valueOf(loginParameter.getData().get("email"));
String password = String.valueOf(loginParameter.getData().get("password"));
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(login, password));
try
(
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
CloseableHttpResponse response = httpClient.execute(request)
)
{
// if there was a failure send it
if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value())
return new ResponseEntity<>(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
// send back the contents
HttpEntity entity = response.getEntity();
if (entity != null)
{
// return it as a String
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.parseMediaType(entity.getContentType().getValue()));
header.setContentLength(entity.getContentLength());
header.set("Content-Disposition", "attachment; filename=" + checkProtectedData.getFileName());
return new ResponseEntity<>(EntityUtils.toByteArray(entity), header, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
FRONTEND
export async function DownloadFile(url, request) {
axios({
url: `${localUrl + url}`, //your url
method: 'POST',
data: request,
responseType: 'blob', // important
}).then((response) =>
{
fileSaver.saveAs(new Blob([response.data]), request.fileName);
return true;
}).catch(function (error)
{
console.error('Failed ', error);
console.error('Failed ', error); console.log('Failed ', error);
}
);
}

How to write java web services to upload image from android and use it in android

I see almost all webservice for android are written in PHP code. With Java I found an example of a rest service to upload image. I coded follow that code but when run test on my android device and Advanced RESTClient of chorme, I get error: HTTP Status 500 - Internal Server Error: Servlet.init () for servlet [Jersey REST Service] threw exception.. My URL: "http://srv.triaxvn.com:8080/logisticwsm/file/image-upload"
In android I use code:
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
File sourceFile = new File(filePath);
String fileName = sourceFile.getName();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(FILE_UPLOAD_URL);
MultipartEntity entity = new MultipartEntity();
// Extra parameters if you want to pass to server
entity.addPart("fileDescription", new StringBody(""));
entity.addPart("fileName", new StringBody(fileName != null ? fileName : sourceFile.getName()));
// Adding file data to http body
FileBody fileBody = new FileBody(sourceFile, "application/octect-stream") ;
entity.addPart("attachment", fileBody);
//totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
My Restful web service code:
#Path("/file")
public class UploadFile {
private final String UPLOADED_FILE_PATH = "c:\\uploaded";
#POST
#Path("/image-upload")
#Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) throws IOException
{
//Get API input data
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
//Get file name
String fileName = uploadForm.get("fileName").get(0).getBodyAsString();
//Get file data to save
List<InputPart> inputParts = uploadForm.get("attachment");
for (InputPart inputPart : inputParts)
{
try
{
//Use this header for extra processing if required
#SuppressWarnings("unused")
MultivaluedMap<String, String> header = inputPart.getHeaders();
// convert the uploaded file to inputstream
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
// constructs upload file path
fileName = UPLOADED_FILE_PATH + fileName;
writeFile(bytes, fileName);
System.out.println("Success !!!!!");
}
catch (Exception e)
{
e.printStackTrace();
return Response.status(200).entity("Uploaded file name : "+e.getMessage()).build();
}
}
return Response.status(200)
.entity("Uploaded file name : "+ fileName).build();
}
//Utility method
private void writeFile(byte[] content, String filename) throws IOException
{
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
}
I do not know the error caused from by android code or Server Restful code and how to fix it

posting image Invalid mime type

I am trying to post an image from my galery to the server from my android device.
They are using Python in the back office.
That's what the Back office developper say:
- Django cannot read the file posted by the Android app in request.FILES. iOS does this properly.
- It seems the the Multipart POST does not properly set the key:value required to properly read the requests.
I am getting this error:
{"errorMessage":"","message":"Invalid mime
type","errorCode":0,"success":false}
Any idea why?
Here is my code:
public static final String IMAGE_JPEG = "image/jpeg";
private HttpEntity getImageEntity() throws Exception {
File imageFile;
Uri originalUri = Uri.parse(this.mFileName);
String originalPath = originalUri.getPath();
boolean isEncrypted = originalPath.contains(FileNames.CACHE_DIR.getPath());
// check if file encrypted or not
if (isEncrypted && ImageLoader.IMAGE_CODING_ENABLED) {
File originalImageFile = new File(originalPath);
String decodedPath = CipherUtils.decryptFile(SmartPagerApplication.getInstance(), originalImageFile);
imageFile = new File(decodedPath);
} else {
imageFile = new File(originalPath);
}
InputStream fis = imageFile.toURI().toURL().openStream();
int rotation = PhotoFileUtils.getOrientation(this.mFileName);
if (rotation > 0) {
byte[] data;
Bitmap rotateBitmap = PhotoFileUtils.checkOrientation(BitmapFactory.decodeStream(fis), rotation);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
rotateBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
data = stream.toByteArray();
stream.close();
rotateBitmap.recycle();
fis.close();
fis = new ByteArrayInputStream(data);
} else {
// data = IOUtils.toByteArray(fis);
}
return getMultipartEntity(originalUri, fis);
}
private MultipartEntity getMultipartEntity(Uri originalPath, InputStream fis) {
InputStreamBody isb = new InputStreamBody(fis, mMimeType, originalPath.getLastPathSegment());
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
"----WebKitFormBoundaryzGJGBFWyGteE24tw", Charset.forName("ISO-8859-1"));
multipartEntity.addPart("binaryFile", isb);
return multipartEntity;
}
private String executePost(String url, HttpEntity params) throws ClientProtocolException, IOException {
Log.e("executePost url =" + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+"----WebKitFormBoundaryzGJGBFWyGteE24tw");
httpPost.addHeader("Cache-Control", "no-cache");
httpPost.setEntity(params);
String response = SmartPagerHTTPClient.getHttpClient().execute(httpPost, new BasicResponseHandler());
return response;
}
I don't have enough reputation to comment, so I have to put this as an answer. In you method getMultipartEntity(), the first line:
InputStreamBody isb = new InputStreamBody(fis, mMimeType, originalPath.getLastPathSegment());
What is the value of mMimeType? Please make sure it's a correct mime type.
This is an OKHttp implementation
first, you need to include it in dependencies:
compile 'com.squareup.okhttp:okhttp:2.4.0'
Actual upload code : Call within an Asynctask
File upload;
upload = new File("<<Your Path to image>>");
Response response;
String finalResponce;
try {
RequestBody body = new MultipartBuilder()
.addFormDataPart("Image", upload.getName(), RequestBody.create(MediaType.parse("image/jpeg"), upload))
.build();
Request request = new Request.Builder()
.url("https://iamin-events.appspot.com/UploadServlet")
.post(body)
.build();
response = new OkHttpClient().newCall(request).execute();
finalResponce = response.body().string();
finalResponce = finalResponce.trim();
mainEventListing.setBackdropUrl(finalResponce);
} catch (Exception e) {
// show error
e.printStackTrace();
}
This is my code for uploading images.The "Content-Type" is like that httpConnection.setRequestProperty("Content-Type", "image/jpeg");
public String doPutUploadImage(File image) throws Exception {
String imageUrl = "http://" + Const.BUCKET_NAME
+ ".oss-cn-hangzhou.aliyuncs.com/" + image.getName();
URL localURL = new URL(imageUrl);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("PUT");
httpConnection.setRequestProperty("Host",
Const.BUCKET_NAME.concat(".oss-cn-hangzhou.aliyuncs.com"));
String GMTDate = SignatureMaker.getGMTDate();
if(!GMTDate.contains("+")){
httpConnection.setRequestProperty("Date", GMTDate);
}else{
GMTDate=GMTDate.substring(0, GMTDate.indexOf("+"));
httpConnection.setRequestProperty("Date", GMTDate);
}
httpConnection.setRequestProperty("Content-Encoding", "UTF-8");
httpConnection.setRequestProperty("Content-Type", "image/jpeg");
httpConnection.setRequestProperty("Content-Length",
String.valueOf(image.length()));
httpConnection.setRequestProperty("Authorization",
"OSS "+ ACCESS_ID+ ":"
+ SignatureMaker.makeSignature(ACCESS_KEY, "PUT",
Const.BUCKET_NAME, image, GMTDate));
sendRequest(httpConnection, image);
return imageUrl;
}
Instead of MultipartEntity, I suggest that you use MultipartEntityBuilder with HttpURLConnection. Then, you can refer to my following code (pay attention to ContentType contentType = ContentType.create("image/jpeg");):
...
byte[] bitmapData = byteArrayOutputStream.toByteArray();
String address = "http://192.168.1.100/api/postfile";
String boundary = "----apiclient----" + System.currentTimeMillis();
String mimeType = "multipart/form-data;boundary=" + boundary;
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setBoundary(boundary);
// Add binary body
if (bitmapData != null) {
ContentType contentType = ContentType.create("image/jpeg"); //CREATE ContentType for the file part
String fileName = "some_file_name.jpeg";
entityBuilder.addBinaryBody("binaryFile", bitmapData, contentType, fileName);
try {
URL url = new URL(address);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", mimeType);
entityBuilder.build().writeTo(urlConnection.getOutputStream());
JSONObject jsonObject = new JSONObject();
try {
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
// process urlConnection.getInputStream();
} else {
// process urlConnection.getErrorStream();
}
jsonObject.put("Message", urlConnection.getResponseMessage());
jsonObject.put("Length", urlConnection.getContentLength());
jsonObject.put("Type", urlConnection.getContentType());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
...
If you still want to use MultipartEntityBuilder with HttpPost, you can refer to the following:
...
byte[] bytes = byteArrayOutputStream.toByteArray();
ContentType contentType = ContentType.create("image/jpeg");
String fileName = "some_filename.jpg";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Add binary body
builder.addBinaryBody("binaryFile", bytes, contentType, fileName);
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
...
You can find out that addBinaryBody in MultipartEntityBuilder class has many implementations such as:
public MultipartEntityBuilder addBinaryBody(String name, InputStream stream, ContentType contentType, String filename)
public MultipartEntityBuilder addBinaryBody(String name, File file, ContentType contentType, String filename)
public MultipartEntityBuilder addBinaryBody(String name, byte[] b, ContentType contentType, String filename)
...
Hope this helps!
I think this issue is because you are setting Content-Type yourself in code, I once had same issue in my case I just removed the Content-Type and It worked. If you remove the Content-Type, you mean that library will detect its Content-Type based on its type.
just remove this line
httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+"----WebKitFormBoundaryzGJGBFWyGteE24tw");
Here is what i am doing and works fine for me -
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("photo", new FileBody(new File(imagePath), "image/jpeg"));
httppost.setEntity(entity);
According to this org.apache.http documentation Change your mime-type static declaration
public static final String IMAGE_JPEG = "image/jpeg";
to
public static final String IMAGE_JPEG = "image/png";
In addition to the #BNK answer Instead of MultipartEntity, you can use MultipartEntityBuilder with HttpURLConnection. In that you can upload the image as a binary body and there you can set the type and the name:
multiPartEntityBuilder.addBinaryBody(imageName, byteArray, ContentType.create("image/png"), "image.png");
You are probably running your code on Android 4.0.x which has buggy implementation for multipart/form-data (httpclient). This issue has been reported earlier and has a work around here

Migrate from Commons HttpClient to HttpComponents Client

I would like to migrate from Commons HttpClient (3.x) to HttpComponents Client (4.x) but having difficulty how to handle redirects. The code works properly under Commons HttpClient but breaks when migrated to HttpComponents Client. Some of the links get undesirable redirects but when I set "http.protocol.handle-redirects" to 'false' a large number links stop working altogether.
Commons HttpClient 3.x:
private static HttpClient httpClient = null;
private static MultiThreadedHttpConnectionManager connectionManager = null;
private static final long MAX_CONNECTION_IDLE_TIME = 60000; // milliseconds
static {
//HttpURLConnection.setFollowRedirects(true);
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(1000); // will need to set from properties file
connectionManager.getParams().setMaxTotalConnections(1000);
httpClient = new HttpClient(connectionManager);
}
/*
* Retrieve HTML
*/
public String fetchURL(String url) throws IOException{
if ( StringUtils.isEmpty(url) )
return null;
GetMethod getMethod = new GetMethod(url);
HttpClient httpClient = new HttpClient();
//configureMethod(getMethod);
//ObjectInputStream oin = null;
InputStream in = null;
int code = -1;
String html = "";
String lastModified = null;
try {
code = httpClient.executeMethod(getMethod);
in = getMethod.getResponseBodyAsStream();
//oin = new ObjectInputStream(in);
//html = getMethod.getResponseBodyAsString();
html = CharStreams.toString(new InputStreamReader(in));
}
catch (Exception except) {
}
finally {
try {
//oin.close();
in.close();
}
catch (Exception except) {}
getMethod.releaseConnection();
connectionManager.closeIdleConnections(MAX_CONNECTION_IDLE_TIME);
}
if (code <= 400){
return html.replaceAll("\\s+", " ");
} else {
throw new Exception("URL: " + url + " returned response code " + code);
}
}
HttpComponents Client 4.x :
private static HttpClient httpClient = null;
private static HttpParams params = null;
//private static MultiThreadedHttpConnectionManager connectionManager = null;
private static ThreadSafeClientConnManager connectionManager = null;
private static final int MAX_CONNECTION_IDLE_TIME = 60000; // milliseconds
static {
//HttpURLConnection.setFollowRedirects(true);
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
connectionManager = new ThreadSafeClientConnManager();
connectionManager.setDefaultMaxPerRoute(1000); // will need to set from properties file
connectionManager.setMaxTotal(1000);
httpClient = new DefaultHttpClient(connectionManager);
// HTTP parameters stores header etc.
params = new BasicHttpParams();
params.setParameter("http.protocol.handle-redirects",false);
}
/*
* Retrieve HTML
*/
public String fetchURL(String url) throws IOException{
if ( StringUtils.isEmpty(url) )
return null;
InputStream in = null;
//int code = -1;
String html = "";
// Prepare a request object
HttpGet httpget = new HttpGet(url);
httpget.setParams(params);
// Execute the request
HttpResponse response = httpClient.execute(httpget);
// The response status
//System.out.println(response.getStatusLine());
int code = response.getStatusLine().getStatusCode();
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
try {
//code = httpClient.executeMethod(getMethod);
//in = getMethod.getResponseBodyAsStream();
in = entity.getContent();
html = CharStreams.toString(new InputStreamReader(in));
}
catch (Exception except) {
throw new Exception("URL: " + url + " returned response code " + code);
}
finally {
try {
//oin.close();
in.close();
}
catch (Exception except) {}
//getMethod.releaseConnection();
connectionManager.closeIdleConnections(MAX_CONNECTION_IDLE_TIME, TimeUnit.MILLISECONDS);
connectionManager.closeExpiredConnections();
}
}
if (code <= 400){
return html;
} else {
throw new Exception("URL: " + url + " returned response code " + code);
}
}
I won't want redirects but under HttpClient 4.x if I enable redirects then I get some that are undesirable, e.g. http://www.walmart.com/ => http://mobile.walmart.com/. Under HttpClient 3.x no such redirects happens.
What do I need to do to migrate HttpClient 3.x to HttpClient 4.x without breaking the code?
It is not the issue with HttpClient 4.x, might be the way target server handle the request, since the user agent is httpclient, it may be handled as mobile (target server may consider other than available browsers like, i.e, chrome, mozilla etc as mobile.)
Please use below code to set it manually
httpclient.getParams().setParameter(
org.apache.http.params.HttpProtocolParams.USER_AGENT,
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"
);

Problem with downloading file from server that uses basic http authentication from my java code

I have written the following java code to download a file from a server that uses http basic authentication. But im getting Http 401 error.I can however download the file by hitting the url directly from the browser.
OutputStream out = null;
InputStream in = null;
URLConnection conn = null;
try {
// Get the URL
URL url = new URL("http://username:password#somehost/protected-area/somefile.doc");
// Open an output stream for the destination file locally
out = new BufferedOutputStream(new FileOutputStream("file.doc"));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
} catch (Exception exception) {
exception.printStackTrace();
}
But,im getting the following exception when i run the program :
java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:password#somehost/protected-area/somefile.doc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at TestDownload.main(TestDownload.java:17)
I am however able to download the file by hitting the url , http://username:password#somehost/protected-area/somefile.doc, directly from the browser.
What could be causing this problem, and any way to fix it ?
Please Help
Thank You.
I'm using org.apache.http:
private StringBuffer readFromServer(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() == null) {
Credentials credentials = new UsernamePasswordCredentials(
Constants.SERVER_USERNAME,
Constants.SERVER_PASSWORD);
authState.setAuthScheme(new BasicScheme());
authState.setAuthScope(AuthScope.ANY);
authState.setCredentials(credentials);
}
}
};
httpclient.addRequestInterceptor(preemptiveAuth, 0);
HttpGet httpget = new HttpGet(url);
HttpResponse response;
InputStream instream = null;
StringBuffer result = new StringBuffer();
try {
response = httpclient.execute(httpget);
etc...

Categories

Resources