HttpURLConnection Get 500 error instead of 401 error - java

When i call a API from postman when i get 401 (accepted code) from postman, but i get 500 from my spring project.
My HttpURLConnection configuration is :
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "Bearer " + token_);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
con.setDoOutput(true);
con.setDoInput(true);
int responseCode = con.getResponseCode();

Related

Error 500 HttpURLConnection but OK in localhost

I am trying to call an endpoint implemented in JAVA with below HttpURLConnection. if i put the path as my aplication running in localhost, everything works great.
But when this application is published into a server(Oracle Weblogic), I get the error:
java.io.IOException: Server returned HTTP response code: 500 for URL: path
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
This error is thrown in below block at the line with **
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "close");
OutputStream os = conn.getOutputStream();
os.write(new Gson().toJson(debtAccountList).getBytes("UTF-8"));
os.flush();
***InputStream in = new BufferedInputStream(conn.getInputStream());***
System.out.println(in.toString());
in.close();
os.close();
conn.disconnect();
}
What makes this works in localhost but not in deployed application?

Sending 'DELETE' request to URL Response Code : 403 in java

I want to delete the API from url : "http://dublr024vm.devlab.ibm.com:60633/B2BiAPIs/svc/cadigitalcertificates/_id:tibco_ssl" , I am getting java.io.IOException: Server returned HTTP response code: 403 for URL. I have passed the correct authentication details too.
Below is the part of my code:
public static void call_me() throws Exception {
InputStream is = null;
String url = "http://dublr024vm.devlab.ibm.com:60633/B2BiAPIs/svc/cadigitalcertificates/_id:tibco_ssl";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
con.setDoOutput(true);
System.setProperty("http.agent", "Chrome");
// optional default is DELETE
con.setRequestMethod("DELETE");
//add request header
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
byte[] message = "admin:password".getBytes("UTF-8");
String encoding = DatatypeConverter.printBase64Binary(message);
con.setRequestProperty("Authorization", "Basic "+new String(encoding));
con.connect();
is = obj.openConnection().getInputStream();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'DELETE' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line, responseText = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
responseText += line;
}
br.close();
con.disconnect();
}

HttpUrlConnection works in Java, 301 in Android

I am trying to write an Android app that on startup automatically authenticates the user at a preset webpage I have no control over. I tried it using a POST-Request (following a GET-Request in order to get the cookies needed for authentication) but I ended up receiving a 301 - Moved Permanently Error.
However, the same code worked perfectly in Java.
InputStream inputStream = null;
int length = 100;
try {
URL url = new URL(site);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", host);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.setRequestProperty("Referer", referer);
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Cookie", cookie);
conn.setInstanceFollowRedirects(false);
conn.setDoInput(true);
conn.setDoOutput(true);
//setting parameters needed for login
List<AbstractMap.SimpleEntry> params = new ArrayList<>();
params.add(new AbstractMap.SimpleEntry("type", type));
params.add(new AbstractMap.SimpleEntry("console", console));
params.add(new AbstractMap.SimpleEntry("login[password]", password));
params.add(new AbstractMap.SimpleEntry("login[mail]", username));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//write converted parameters
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response + "\n" + conn.getResponseMessage());
inputStream = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = convertInputStreamToString(inputStream, length);
Log.d(TAG, "Content of Webpage: " + contentAsString);
} finally {
if (inputStream != null) {
inputStream.close();
}
}

httpurlConnection with httpParams in java

I'm trying to post a file from local to another platform over a switch. When i do it with DefaultHttpClient there is no problem.
HttpParams params = new BasicHttpParams();
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName(interfaceIp));
DefaultHttpClient httpClientPost = new DefaultHttpClient(params);
But i have to do it with HttpURLConnection. Is there a way to do this?
for example:
httpConn = (HttpURLConnection) url.openConnection(myHttpParams);
here is my HttpUrlConn codes
url = new URL(baseUrl+"/html/uploadimage.cgi");
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +"----WebKitFormBoundary"+boundary);
httpConn.setRequestProperty("Host", "192.168.1.1");
httpConn.setRequestProperty("Connection", "keep-alive");
httpConn.setRequestProperty("Content-Length", "16551361");
httpConn.setRequestProperty("Cache-Control", "max-age=0");
httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpConn.setRequestProperty("Origin", "http://192.168.1.1");
httpConn.setRequestProperty("Upgrade-Insecure-Requests", "1");
httpConn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36");
httpConn.setRequestProperty("Referer", baseUrl + "/html/advance.html");
httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
httpConn.setRequestProperty("Accept-Language", "tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4");
String cookie = "Username="+ username +"; " +
"Password="+ cyreptedPassword +"; Language=tk; " +
"username="+ username +"; " +
"SessionID_R3="+ sessionID +"; activeMenuID=maintain_settings; activeSubmenuID=device_mngt";
httpConn.setRequestProperty("Cookie", cookie);
httpConn.setAllowUserInteraction(true);
httpConn.setConnectTimeout(9999*9999999);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
thanks for all.
HttpUrlConnection does not use http params, but it uses proxy.
here is some information about httpUrlConnection example.

Web client with request headers

My code in .net is as the following code. I want to write it in java. How can I do it? Shoul I use httpclient or socket to do this?
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("HOST", "example.com");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
wc.Headers.Add("Accept-Language", "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3");
html = wc.DownloadString(link);
if (temp == null)
return string.Empty;
return html;
}
Use HttpUrlConnection as it comes with default JDK. No extra libraries are need to be downloaded.
Here is the translation for above piece of code in java
public static String get(String link){
HttpURLConnection connection=null;
try{
URL url=new URL(link);
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("HOST", "example.com");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Language", "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3");
connection.setDoInput(true);
connection.setDoOutput(true);
BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line,response="";
while((line=in.readLine())!=null)
response+=(line+"\n");
in.close();
return response;
}catch(Exception e){}
return "";
}

Categories

Resources