Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 653099
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:20:41+00:00 2026-05-13T22:20:41+00:00

I’m making call to Alfresco Webscripts which return JSON. I do this using GET

  • 0

I’m making call to Alfresco Webscripts which return JSON. I do this using GET requests which all work perfectly. If I do a file POST however, the Alfresco server receives the file correctly and sends back a JSON response, but this time the response causes the browser to prompt for a download instead of the letting Javascript process the callback.

Now all these calls are going through a “home made” reverse proxy (see below) which uses HttpUrlConnection. This proxy routes all the calls to an Alfresco running on another host. Everything else works fine (pngs, text, html, GET requests,even authentication). In both GET and POST responses the Content-Type is “application/json;charset=UTF-8”

Many thanks for any responses.

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;

public class ReverseProxy extends GenericServlet{

public static final String SERVER_URL = "serverURL";
protected String serverURL;
protected boolean debug;

public ReverseProxy(){
}

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    debug = Boolean.valueOf(config.getInitParameter("debug")).booleanValue();
    serverURL = config.getInitParameter("serverURL");
    if(serverURL == null){
        throw new ServletException("ReverseProxy servlet initialization parameter 'serverURL' not defined");
    }
}

public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
    InputStream inputStream;
    OutputStream outputStream;
    Exception exception;
    if(debug){System.out.println("ReverseProxy.service()");}
    HttpServletRequest request;
    HttpServletResponse response;
    try{
        request = (HttpServletRequest)req;
        response = (HttpServletResponse)resp;
    }
    catch(ClassCastException e){
        throw new ServletException("non-HTTP request or response");
    }
    String method = request.getMethod();
    StringBuffer urlBuffer = new StringBuffer();
    urlBuffer.append(serverURL);
    urlBuffer.append(request.getServletPath());
    if(request.getPathInfo() != null)
        urlBuffer.append(request.getPathInfo());
    if(request.getQueryString() != null){
        urlBuffer.append('?');
        urlBuffer.append(request.getQueryString());
    }
    URL url = new URL(urlBuffer.toString());

    //pass authentication
    String user=null, password=null;

    Set entrySet = req.getParameterMap().entrySet();
    Map headers = new HashMap();
    for ( Object anEntrySet : entrySet ) {
        Map.Entry header = (Map.Entry) anEntrySet;
        String key = (String) header.getKey();
        String value = ((String[]) header.getValue())[0];
        if ("user".equals(key)) {
            user = value;
        } else if ("password".equals(key)) {
            password = value;
        }else {
            headers.put(key, value);
        }
    }

    String userpass = null;
    if (user != null && userpass!=null) {
        userpass = user+":"+password;
    }
    String auth = request.getHeader("Authorization");
    if(auth != null){
        if (auth.toUpperCase().startsWith("BASIC ")){
            String userpassEncoded = auth.substring(6);
            userpass = new String(Base64.decodeBase64(userpassEncoded.getBytes()));
        }
    }

    String digest=null;
    if (userpass!=null) {
        if(debug){System.out.println("ReverseProxy found userpass:" + userpass);}
        digest = "Basic " + new String(Base64.encodeBase64((userpass).getBytes()));
    }
    else{
        if(debug){System.out.println("ReverseProxy found no auth credentials");}
    }

    //do connection
    HttpURLConnection connection = null;
    connection = (HttpURLConnection) url.openConnection();
    if (digest != null) {connection.setRequestProperty("Authorization", digest);}

    connection.setRequestMethod(method);
    connection.setDoInput(true);

    if(method.equals("POST")){
        if(request.getHeader("Content-Type") != null){
            if(debug){System.out.println("ReverseProxy Content-Type: " + request.getHeader("Content-Type"));}
            if(debug){System.out.println("ReverseProxy Content-Length: " + request.getHeader("Content-Length"));}
            if(request.getHeader("Content-Type").indexOf("multipart/form-data") != -1){
                connection.setRequestProperty("Content-Type", request.getHeader("Content-Type"));
                connection.setRequestProperty("Content-Length", request.getHeader("Content-Length"));
            }
        }
        connection.setDoOutput(true);
    }
    if(debug){
        System.out.println((new StringBuilder()).append("ReverseProxy: URL=").append(url).append(" method=").append(method).toString());
    }

    //set headers
    Set headersSet = headers.entrySet();
    for ( Object aHeadersSet : headersSet ) {
        Map.Entry header = (Map.Entry) aHeadersSet;
        connection.setRequestProperty((String) header.getKey(), (String) header.getValue());
    }

    connection.connect();
    inputStream = null;
    outputStream = null;
    try{
        if(method.equals("POST")){
            javax.servlet.ServletInputStream servletInputStream = request.getInputStream();
            outputStream = connection.getOutputStream();
            copy(servletInputStream, outputStream);
        }
        response.setContentLength(connection.getContentLength());
        response.setContentType(connection.getContentType());
        if(debug){System.out.println("ReverseProxy Connection Content-Type: " + connection.getContentType());}
        response.setCharacterEncoding(connection.getContentEncoding());
        String cacheControl = connection.getHeaderField("Cache-Control");
        if(cacheControl != null){
            response.setHeader("Cache-Control", cacheControl);
        }
        int responseCode = connection.getResponseCode();
        response.setStatus(responseCode);

        if(responseCode == 401){
            response.setHeader("WWW-Authenticate", "Basic realm=\"Login Required\"");
        }

        for( Iterator i = connection.getHeaderFields().entrySet().iterator() ; i.hasNext() ;){
            Map.Entry mapEntry = (Map.Entry)i.next();
            if(mapEntry.getKey()!=null){
                response.setHeader(mapEntry.getKey().toString(), ((List)mapEntry.getValue()).get(0).toString());
            }
        }

        //if(debug){System.out.println("ReverseProxy Connection Content-Disposition: " + connection.getHeaderField("Content-Disposition"));}

        if(debug){System.out.println((new StringBuilder()).append("ReverseProxy: response code '").append(responseCode).append("' from ").append(url).toString());}
        if (responseCode == 200 || responseCode == 201) {
            inputStream = connection.getInputStream();
        }
        else{
            inputStream = connection.getErrorStream();
        }

        javax.servlet.ServletOutputStream servletOutputStream = response.getOutputStream();
        copy(inputStream, servletOutputStream);
    }
    catch(IOException ex){
        if(debug)
            ex.printStackTrace();
        throw ex;
    }
    finally{
        //if(inputStream == null) goto _L0; else goto _L0
        //break;
    }
    if(inputStream != null){
        inputStream.close();
    }
    if(outputStream != null){
        outputStream.close();
    } 
    inputStream.close();
    if(outputStream != null){
        outputStream.close();
    }
    //throw exception;
}

public long copy(InputStream input, OutputStream output) throws IOException{
    byte buffer[] = new byte[4096];
    long count = 0L;
    for(int n = 0; -1 != (n = input.read(buffer));){
        output.write(buffer, 0, n);
        count += n;
    }

    output.flush();
    if(debug)
        System.err.println((new StringBuilder()).append("copy ").append(count).append(" bytes").toString());
    return count;
}

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:20:41+00:00Added an answer on May 13, 2026 at 10:20 pm

    I guess the problem is more in the client side or a misconception in your side. It’s correct behaviour if the browser prompts to download the file when it has a content type of application/json, because the browser itself doesn’t know how to handle it. The browser can only display everything which matches a content type of at least text/* or image/*.

    Normally, JSON responses are to be handled internally by JavaScript, which can perfectly handle ajaxical responses with a content type of application/json. You can test it by changing it to text/plain or text/javascript, you’ll see that the browser will display it (because it matches text/*). But for JSON the correct content type is indeed application/json. Just keep it as is and use the right tools to download/open the JSON 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 368k
  • Answers 368k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The Entity Framework designer is terrible - I've had the… May 14, 2026 at 5:11 pm
  • Editorial Team
    Editorial Team added an answer If by "hijack" you meant sniff the packets then what… May 14, 2026 at 5:11 pm
  • Editorial Team
    Editorial Team added an answer If you want two actions to be atomic, embed them… May 14, 2026 at 5:11 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.