DELETE Request in Android doesn't connect to server - java

So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.

You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.

If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();

Related

java.net.URL giving security vulnerability during code scan

I have the below method to check an incoming url is valid or not and based on this i need to redirect to error page.
/*
* This method is used to validate the URL and return a response
*/
private static int isValidUrl(String qrUrl) {
int code = 0;
try {
URL url = new URL(qrUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
code = connection.getResponseCode();
logger.info("Response code is {} for the url", code);
} catch(MalformedURLException e) {
logger.error("A MalformedURLException Occured in QR Code servlet during URL Validation", e);
} catch (IOException e) {
logger.error("An IOException Occured in QR Code servlet during URL Validation", e);
}
return code;
}
The below line of code is giving medium security vulnerability(Description:
This web server request could be used by an attacker to expose internal services and filesystem) during code scan. How can I fix it?

Before I can get JSON file, how can I build correct connection with getting 503 Server Error

I was trying several days to get HTTPS connection right to connect to Yobit public API. I don't know what happen to my code. I have tried so many different examples but nothing works out on Yobit. Those codes and examples I have tried, they either give 411, 503 error or MalFormException:no protocol. Can anyone help me? I have very limited experience with HTTPS or web programming on Java. If any one can provide me solutions and references, I will really appreciate that.
public void buildHttpsConnection()
{
try {
URL url = new URL("https://yobit.net/api/3/info");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("user-Agent", "Mozilla/5.0 (compatible; JAVA AWT)");
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
con.setDoOutput(true);
con.setUseCaches(false);
System.out.println(con.getResponseCode());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Try to use "https://www.yobit.net/api/3/info" URL Instead of "https://yobit.net/api/3/info"
It will give you the same result. You can validate it from the browser Window.
Check below snippet.
try {
URL url = null;
try {
url = new URL("https://www.yobit.net/api/3/info");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
try {
con.setRequestMethod("GET");
} catch (ProtocolException e1) {
e1.printStackTrace();
}
con.setRequestProperty("user-Agent", "Mozilla/5.0 (compatible; JAVA AWT)");
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
con.setDoOutput(true);
con.setUseCaches(false);
con.connect();
try {
System.out.println(con.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}

Handling java.net.HttpURLConnection to server that does not exist

Upon trying to connect to a host/server that does not exist, my program just seems to die. Stepping through with the debugger lends me nothing, it makes it to getResponseCode() and then just stops working. No exceptions are thrown from what I can tell and the program doesn't return.
Here is the relevant code snippet:
try {
//construct a URL and open the connection
URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
if(http.getResponseCode() != 200) {
System.out.println("Could not connect");
}
System.out.println("Connected");
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) { //give me something please
e.printStackTrace();
return;
}
When connecting to a valid URL, it works fine.
I fixed it, I needed to add http.setConnectTimeout(10000); after I opened the connection. Apparently whatever the default timeout was set as was so long that it appeared to never give a response at all, even when leaving the application open for several minutes.

Can't connect with URL connection

I am trying to connect to a website where the site database adds a name to a list based on the url you connect with. I can't connect. The site works and I can access it in a browser. The error is an IOException.
if ((Boolean) value)
{
System.out.println("setValue");
try
{
URL myURL = new URL("http://app.bannervision.tv/api/add/" + data.name.get(row));
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e)
{
System.out.println("MalformedURLException");
// ...
}
catch (IOException e)
{
System.out.println("IOException");
System.out.println("http://app.bannervision.tv/api/add/" + data.name.get(row));
// openConnection() failed
// ...
}
}

401 response when reading tweets

I'm new to mobile apps development. I'm developing a blackberry application which reads tweets from the user's timeline. So far I managed to get the OAuth access token. The problem happens when I try to use this access token to read the tweets I get a 401 response with a message "Unauthorized". I'm not using any libraries I'm doing everything on my own. Could anyone help me with this?
Thanks,
Here's the code:
HttpConnectionFactory factory = new HttpConnectionFactory( url,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length", Integer.toString(header.getBytes().length));
os = httpConn.openOutputStream();
os.write(header.getBytes());
os.close();
os = null;
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
// Dialog.alert(httpConn.getDate()+" : "+System.currentTimeMillis());
if (resp == HttpConnection.HTTP_OK) {
XMLReader parser;
try {
parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
parser.parse(new InputSource(input));
for(int i=0 ; i<2 ; i++)
{
tweets.addElement( parser.getProperty("text").toString());
Dialog.alert(parser.getProperty("text").toString());
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dialog.alert("your tweet was posted successfully :)");
}
Dialog.alert(httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
return (httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not an expert in OAuth, however just a note:
This:
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
and this:
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
are mutually exclusive things. You are posting data to server, so it should be a POST (not GET).

Categories