Recently I needed to move some code from Java to C#.
This is one of the methods that I couldn't rewrite... can someone help me?
public static String coreApiPostRequest(URL url, String input) {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
String responseMessage=null;
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
responseMessage = output;
}
conn.disconnect();
return responseMessage;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Related
Im reading a simple text file from my website using HttpURLConnection, and when it calls getInputStream it freezes and never finishes, the getResponseCode returns 200. It was working at first every time then it stopped working.
I have search for a solution all over the internet and none work. I think it maybe ddos protection on the web server, or something on there end blocking it.
public static String getLatestInfo(String urlString){
URL url = null;
HttpURLConnection connection = null;
/*InputStream inputStream = null;
InputStreamReader isr = null;
BufferedReader in = null;*/
try {
url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
//connection.setRequestMethod("GET");
//connection.setDoOutput(true);
connection.setConnectTimeout(5000); // 5 seconds connectTimeout
connection.setReadTimeout(5000); // 5 seconds socketTimeout
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Accept", "text/xml");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
connection.connect();
if (connection.getResponseCode() == 200) {
try(InputStream inputStream = connection.getInputStream())
{
try(InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8")) {
try(BufferedReader in = new BufferedReader(isr))
{
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;
}
}
}
/*inputStream = connection.getInputStream();
isr = new InputStreamReader(inputStream, "UTF-8");
in = new BufferedReader(isr);
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;*/
}
}
catch (SocketTimeoutException e)
{
System.out.println("Timeout: " + e.getMessage());
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
try {
System.out.println(connection.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
finally {
if (connection != null) connection.disconnect();
/*try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (isr != null) isr.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
return null;}
I started simple and have added all the suggestion that should've fix it.. it gets response code 200 and then freezes on connection.getInputStream()
There were multiple things wrong in my code:
Some streams for file reading wasn't closed.
I was using FileInputStream/FileOutputStream and it was making it freeze. This explains it. Even though it shows a work around, but it still would make it freeze.
The main problem i was using SwingUtilities.invokeLater(new Runnable ()... and it was freeze and random points.
Fixing all the above factors and it solved my problem.
Hi Below is the piece of code. In the below code, when i close writer after write, server gives expected results. But if it is closed in finally block it return 400 bad request. Is there any reason for this behavior?
BufferedReader br = null;
HttpURLConnection conn = null;
OutputStreamWriter writer = null;
String ip = "test"
try {
URL url = new URL(http://someurl));
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setConnectTimeout(0);
conn.setRequestProperty("Content-Type", "application/json");
writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(ip);
// writer.close();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
} catch (final Exception e) {
LOG.error("Error" + e);
}
finally
{
//Closing writer in finally block.
if(writer != null)
{
try
{
writer.close();
}
catch (IOException e) {
LOG.error("Error in closing Writer", e);
}
}
if (br != null)
{
try
{
br.close();
}
catch (final IOException e)
{
LOG.error("Error: ", e);
}
}
if(conn != null){
conn.disconnect();
}
}
You need to flush the contents to server. Use writer.flush() instead of writer.close() once you are done with writing request, just before reading response.
I want to invoke remote server using HttpURLConnection, here is my function:
public String invokeAwvsServer(String api, String param, String method){
System.out.println(api+param);
BufferedReader reader = null;
HttpURLConnection connection = null;
OutputStreamWriter out = null;
try {
URL url = new URL(api);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth", apiKey);
connection.connect();
if(method.equalsIgnoreCase("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuffer res = new StringBuffer();
while ((line = reader.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
I use this function in its own class and works well, but if I call it in other class ,the remote server return 500 status code and JVM throws exception like:
java.io.IOException: Server returned HTTP response code: 500 for URL:...
What`s the reason?Thanks a lot:)
I'm trying to perform a "PUT" but nothing happens, i don't catch any exception either.
Here is what I've tried:
String destinationUrl = 'http://stash.myDomain.com/rest/api/1.0/projects/myProj/permissions/users?name=myUser&permission=PROJECT_WRITE';
URL url = null;
try {
url = new URL(destinationUrl)
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
String userpass = STASH_USERNAME + ":" + STASH_PASSWORD;
String basicAuth = "Basic " + converter.printBase64Binary(userpass.getBytes());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Authorization", basicAuth)
//httpURLConnection.setRequestProperty("Content-Type", "application/json");
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes("Hello");
} catch (IOException excepption) {
excepption.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Any idea what should i do ?
I'm trying to POST some data to an https url, in my android application, in order to get a json format response.
I'm facing two problems:
is = conn.getInputStream();
throws
java.io.FileNotFoundException
I don't get if i do something wrong with HttpsURLConnection.
The second problem arose when i debug the code (used eclipse); I set a breakpoint after
conn.setDoOutput(true);
and, when inspecting conn values, I see that the variable doOutput remain set to false and type GET.
My method for https POST is the following, where POSTData is a class extending ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
A little update: apparently eclipse debug lied to me, running and debugging on netbeans shows a POST connection. Error seems to be related to parameters i'm passing to the url.
FileNotFoundException means that the URL you posted to doesn't exist, or couldn't be mapped to a servlet. It is the result of an HTTP 404 status code.
Don't worry about what you see in the debugger if it doesn't agree with how the program behaves. If doOutput really wasn't enabled, you would get an exception obtaining the output stream.