Java connection exception 500

Webservice call returns error 500

I have started a small project in Java.
I have to create a client which will send xml to a url as a HTTP POST request.
I try it using java.net.* package (Following is the piece of code) but I am getting error as follows:

java.io.IOException: Server returned HTTP response code: 500 for URL: "target url" at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441) at newExample.main(newExample.java:36) 
try < URL url = new URL("target url"); URLConnection connection = url.openConnection(); if( connection instanceof HttpURLConnection ) ((HttpURLConnection)connection).setRequestMethod("POST"); connection.setRequestProperty("Content-Length", Integer.toString(requestXml.length()) ); connection.setRequestProperty("Content-Type","text/xml; charset:ISO-8859-1;"); connection.setDoOutput(true); connection.connect(); // Create a writer to the url PrintWriter writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream())); // Get a reader from the url BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); writer.println(); writer.println(requestXml); writer.println(); writer.flush(); String line = reader.readLine(); while( line != null ) < System.out.println( line ); line = reader.readLine(); >> catch (MalformedURLException e) < e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >

Please help with suitable examples or any other ways of doing this. Point errors/mistakes in above code or other possibilities. My Web Service is in spring framework xml to send is in the string format: requestXml

HTTP error 500 is «internal server error» a generic error returned when the service encounters an error, or throws an exception. You might want to read the full response body and see if has any further information

error code 500 is an Internal Server Error. So I’d concentrate on the server rather than the client really.

Читайте также:  All collections methods in java

If your URL is correct (can check from browser), there is not much that you can do. Looks like server side error.

5 Answers 5

The problem lies in below code

// Get a reader from the url BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

As the service might not always return you the proper response. as you are calling a service through http, it can be possible that the server itself is not available or the service is not available. So you should always check for the response code before reading response from streams, based on the response code you’ve to decide whether to read it from inputStream for success response or from errorStream for failure or exception condition.

BufferedReader reader = null; if(connection.getResponseCode() == 200) < reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); >else

This would resolve the problem

getResponeCode, does this method actually exists? I dont find it here — docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html

The problem is inside your server code or the server configuration:

10.5.1 500 Internal Server Error

The server encountered an unexpected condition which prevented it from fulfilling the request.

If the server is under your control (should be, if I look at the URL [before the edit]), then have a look at the server logs.

Well, you should close your streams and connections. Automatic resource maangement from Java 7 or http://projectlombok.org/ can help. However, this is probably not the main problem.

The main problem is that the server-side fails. HTTP code 500 means server-side error. I can’t tell you the reason, because I don’t know the server side part. Maybe you should look at the log of the server.

I think that your problem is that you are opening the input stream before you have written and closed the output stream. Certainly, the Sun Tutorial does it that way.

If you open the input stream too soon, it is possible that the output stream will be closed automatically, causing the server to see an empty POST request. This could be sufficient to cause it to get confused and send a 500 response.

Even if this is not what is causing the 500 errors, it is a good idea to do things in the order set out in the tutorial. For a start, if you accidentally read the response before you’ve finished writing the request, you are likely to (at least temporarily) lock up the connection. (In fact, it looks like your code is doing this because you are not closing the writer before reading from the reader.)

A separate issue is that your code does not close the connection in all circumstances, and is therefore liable to leak network connections. If it does this repeatedly, it is likely to lead to more IOExceptions.

Источник

Error 500 HttpUrlConnection java

I was using AsyncHttpClient to make some requests to my database and It was working fine. But, when I tried to use 3g on my mobile, it simply didn’t work. That’s why I decided to change HttpClient to HttpUrlConnection (people said that it works better with 3g + wifi). But, when I was coding it, I just got stuck at a buffer problem that I can’t solve. The code is:

public class SendPostRequest extends AsyncTask < String base64CredenciaisCodificadas; HashMap postDataParam; @Override protected String doInBackground(String. url) < String response = ""; try< URL link = new URL(url[0]); HttpURLConnection e = (HttpURLConnection)link.openConnection(); e.setReadTimeout(15000); e.setConnectTimeout(15000); e.setRequestMethod("POST"); e.setRequestProperty("Authorization", "Basic " + base64CredenciaisCodificadas); e.setDoInput(true); e.setDoOutput(true); e.setFixedLengthStreamingMode(getPostDataString(postDataParam).length()); OutputStream os = e.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParam)); writer.flush(); writer.close(); os.close(); int responseCode = e.getResponseCode(); if (responseCode == 200)< //Code to get data from web service. >> catch(Exception e) < >return response; > private String getPostDataString(HashMap params) throws UnsupportedEncodingException < StringBuilder result = new StringBuilder(); boolean first = true; Iterator var4 = params.entrySet().iterator(); while(var4.hasNext()) < Map.Entry entry = (Map.Entry)var4.next(); if(first) < first = false; result.append("?"); >else < result.append("&"); >result.append(URLEncoder.encode((String)entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode((String)entry.getValue(), "UTF-8")); > return result.toString(); > > 
10-25 15:16:11.128 30807-30898/petma.testesappcarona I/System.out: Stat: 500; Msg: buffer(com.android.okhttp.internal.http.HttpConnection$UnknownLengthSource@834db8).inputStream() 

If anyone has any more doubts, please just ask and I will send additional data. Edit: It is android. It has permission to internet at manifest.

Источник

Why do I get an error 500 when I send a GET request?

I am trying to send a simple GET request, as it is explained here : Using java.net.URLConnection to fire and handle HTTP requests The web page I’m pointing to is : https://e-campus.hei.fr/ERP-prod/ And I get this HTTP500 error :

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: https://e-campus.hei.fr/ERP-prod/ at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234) at GetWebPage.main(GetWebPage.java:14) 

Why do I receive this error for this page ? The code i wrote will return me the source code of any other web page. My code :

public class GetWebPage < public static void main(String args[]) throws MalformedURLException, IOException < URLConnection connection = new URL("https://e-campus.hei.fr/ERP-prod/").openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); InputStream response = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(response); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = reader.readLine()) != null) < sb.append(line + "\n"); >System.out.println(sb.toString()); > 

Same stuff posted the other day on daniweb. It did not get reply for same reason, weak problem description, missing code

3 Answers 3

The standard java.net.URL class doesn’t support the HTTPS protocol. You must set a system property and add a new security provider to the Security class object. There are a variety of ways to do both of these things, but try this :

System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 

append the port number if different from 443

URL url = new URL("https://[your server]:7002"); URLConnection con = URL.openConnection(); //SSLException thrown here if server certificate is invalid con.getInputStream(); 

you have to catch SSLException if certificate is not trusted.

final code look like this :

System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); try < //if we have the JSSE provider available, //and it has not already been //set, add it as a new provide to the Security class. Class clsFactory = Class.forName("com.sun.net.ssl.internal.ssl.Provider"); if( (null != clsFactory) && (null == Security.getProvider("SunJSSE")) ) Security.addProvider((Provider)clsFactory.newInstance()); >catch( ClassNotFoundException cfe ) < throw new Exception("Unable to load the JSSE SSL stream handler." + "Check classpath." + cfe.toString()); >URL url = new URL("https://[your server]:7002"); URLConnection con = URL.openConnection(); //SSLException thrown here if server certificate is invalid con.getInputStream(); 

Источник

Java HTTPUrlConnection returns 500 status code

When I print the headerfields, it shows the 500 code.. when I change the URL to something else like google.com , it works fine. But I don’t understand why it doesn’t work here but it works fine on the browser and with curl. Any help would be highly appreciated.. Thank you,

8 Answers 8

This is mostly happening because of encoding. If you are using browser OK, but getting 500 ( internal server error ) in your program,it is because the browsers have a highly sophisticated code regarding charsets and content-types.

Here is my code and it works in the case of ISO8859_1 as charset and english language.

public void sendPost(String Url, String params) throws Exception < String url=Url; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestProperty("Acceptcharset", "en-us"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("charset", "EN-US"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); String urlParameters=params; // Send post request con.setDoOutput(true); con.setDoInput(true); con.connect(); //con. DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) < response.append(inputLine); >in.close(); //print result System.out.println(response.toString()); this.response=response.toString(); con.disconnect(); > 

and in the main program , call it like this:

myclassname.sendPost("https://change.this2webaddress.desphilboy.com/websitealias/orwebpath/someaction","paramname="+URLEncoder.encode(urlparam,"ISO8859_1")) 

The status code 500 suggests that the code at web server have been crashed .Use HttpURLConnection#getErrorStream() to get more idea of the error. Refer Http Status Code 500

I ran into the problem of «URL works in browser, but when I do http-get in java I get a 500 Error».

In my case the problem was that the regular http-get ended up in an infinite redirect loop between /default.aspx and /login.aspx

 URL oUrl = new URL(url); HttpURLConnection con = (HttpURLConnection) oUrl.openConnection(); con.setRequestMethod("GET"); . int responseCode = con.getResponseCode(); 

What was happening was: The server serves up a three-part cookie and con.getResponseCode() only used one of the parts. The cookie data in the header looked like this:

header.key = null value = HTTP/1.1 302 Found . header.key = Location value = /default.aspx header.key = Set-Cookie value = WebCom-lbal=qxmgueUmKZvx8zjxPftC/bHT/g/rUrJXyOoX3YKnYJxEHwILnR13ojZmkkocFI7ZzU0aX9pVtJ93yNg=; path=/ value = USE_RESPONSIVE_GUI=1; expires=Wed, 17-Apr-2115 18:22:11 GMT; path=/ value = ASP.NET_SessionId=bf0bxkfawdwfr10ipmvviq3d; path=/; HttpOnly . 

So the server when receiving only a third of the needed data got confused: You’re logged in! No wait, you have to login. No, you’re logged in, .

To work around the infinite redirect-loop I had to manually look for re-directs and manually parse through the header for «Set-cookie» entries.

 con = (HttpURLConnection) oUrl.openConnection(); con.setRequestMethod("GET"); . log.debug("Disable auto-redirect. We have to look at each redirect manually"); con.setInstanceFollowRedirects(false); . int responseCode = con.getResponseCode(); 

With this code the parsing of the cookie, if we get a redirect in the responseCode:

private String getNewCookiesIfAny(String origCookies, HttpURLConnection con) < String result = null; String key; Set>> allHeaders = con.getHeaderFields().entrySet(); for (Map.Entry> header : allHeaders) < key = header.getKey(); if (key != null && key.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) < // get the cookie if need, for login Listvalues = header.getValue(); for (String value : values) < if (result == null || result.isEmpty()) < result = value; >else < result = result + "; " + value; >> > > if (result == null) < log.debug("Reuse the original cookie"); result = origCookies; >return result; > 

Источник

Оцените статью