1

The following snippet tries to send 2 parameters along with a URL to a servlet. But when I try this snippet,I get a message :

Connection to file server failed

But if I directly try the URL :

http://localhost:8084/nappster/ReceiveFileName?fileName=" + fileName + "&ip=" + IP

with the data, there is no problem. Servlet receives the file name and processes it as expected. What could be the reason that when I try to connect to the URL via code, it fails and succeeds when trying in a browser.

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String fileName = request.getParameter("FileTag");
    String IP = new ClientAddress().getNetworkIP();                
    // Send the file name to the nappster server 
    URL url = new URL("http://localhost:8084/nappster/ReceiveFileName?fileName=" + fileName + "&ip=" + IP);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if(connection.getResponseCode() == 200) {
        // File name sent successfully to the server
        System.out.println("Connection to file server successful");
        System.out.println("--------");
    } else {
        // Unable to send file name to the server
        System.out.println("Connection to file server failed");

     }
}

NOTE :

Response code returned when I try the above snippet is 505

saplingPro
  • 20,769
  • 53
  • 137
  • 195
  • 1
    What is the `responseCode` returned? – Alexis Pigeon Jan 04 '13 at 14:51
  • can you print the value of `connection.getResponseCode()` when you get your response code ? – Majid Laissi Jan 04 '13 at 14:52
  • That is HTTP version not supported... I think HttpUrlConnection is v1.0 only, you might want to try something like HttpComponents (http://hc.apache.org/) instead - the server may require 1.1. – cjstehno Jan 04 '13 at 15:07
  • @cjstehno but when I am trying in another servlets it works fine. For example `http://localhost:8084/nappster/ReceiveInformation?" + information` – saplingPro Jan 04 '13 at 15:14
  • There might be redirect which you do not notice in your browser - try to print more data instead of just System.out.println("Connection to file server failed"); – Hurda Jan 04 '13 at 14:51

1 Answers1

1

Try using url.encode() method.

Mukund K Roy
  • 175
  • 1
  • 8