Send PUT, DELETE HTTP request in HttpURLConnection - java

I have created web service call using java below code. Now I need to make delete and put operations to be perform.
URL url = new URL("http://example.com/questions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();
When I add below code to perform DELETE action it gives errors saying:
java.net.ProtocolException: HTTP method DELETE doesn't support output.
conn.setRequestMethod( "DELETE" );
So how to perform delete and put requests?

PUT example using HttpURLConnection:
URL url = null;
try {
url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write("hello");
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}
DELETE example using HttpURLConnection:
URL url = null;
try {
url = new URL("http://localhost:8080/deleteservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
System.out.println(httpURLConnection.getResponseCode());
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}

FOR PUT
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
FOR DELETE
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
Actually got it from the link here:
Send PUT, DELETE HTTP request in HttpURLConnection

i suggest you to use restlet client for web service request .please refer the bellow sample code ,it may help you
Client client = new Client(new Context(), Protocol.HTTP);
clientResource = new ClientResource(url);
ResponseRepresentation responseRep = null;
try {
clientResource.setNext(client);
clientResource.delete();
} catch (Exception e) {
e.printStackTrace();
}

Related

How to call subsequent request using j_security_check

How to call subsequent requests using j_security_check, I have followed below code but it's not working .
String url = "https://myhost/jsp/j_security_check?j_username=myuser&j_password=mypassword";
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
if (connection.getResponseCode() == 200) {
String cookie = connection.getHeaderField("Set-Cookie").split(";", 2)[0];
url = "https://myhost/getusers";
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("Cache-Control", "no-cache");
InputStream input = connection.getInputStream();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String result = buffer.lines().collect(Collectors.joining("\n"));
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
Can anyone help me on it.

Call httpconnection with encoding not working

i need to call a service get using http connection, the response contains arabic characters, but when i call it using the code below
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
the reponse is
1|U|����� ������|$2|L|���� �������|$3|S|����
I tried another solution not using Commons-io but also not working
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
//Log.e("statusCode", "" + statusCode);
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
sb.append(tmp, 0, l);
}
//sb = buffer.toString();
}
connection.disconnect();
if (sb != null)
serverResponse = sb.toString();
Do i need to change anything from web service??? but when i call it from browser all characters show clearly with no problem
any suggestion?
Maybe the server is not using UTF-8, your code is trying to use UTF-8 to decode the data but that will only work if the server is using the same encoding.
The browser works because maybe it is using the HTTP header "Content-Encoding" which should indicate the encoding used for the data.
Please decode your string response
String dateStr = URLDecoder.decode(yourStringResponse, "utf-8");

Java - Put Request

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 ?

FileNotFoundException on HttpsURLConnection with POST and unmutable doOutput variable

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.

Does closing of input/output stream gotten from getInput/OutputStream() affects recreation of underlying Socket?

I've already looked through resources which describe specifics of work with HttpURLConnection as in Java so in Android (where there is not default implementation of working with connection pool) and my question is: if I close a stream gotten from HttpURLConnection, will the system create a new one Socket at a next time when I establish a HttpURLConnection with the same URL or it will try to use an exist one? Considering the following code:
private byte[] downloadText(URL url, String data) {
OutputStream out = null;
InputStream in = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("POST");
conn.setReadTimeout(20 * 1000);
conn.setConnectTimeout(15 * 000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
byte[] payload = data.getBytes("utf-8");
conn.setFixedLengthStreamingMode(payload.length);
conn.connect();
out = new BufferedOutputStream(conn.getOutputStream());
out.write(payload);
out.flush();
final int responseCode = conn.getResponseCode();
final String responseMessage = conn.getResponseMessage();
is = conn.getInputStream();
if((responseCode / 100) == 2 || responseMessage.equals("OK")) {
return readFromStream(is);
}
} catch (IOException e) {
Log.e(TAG, "Error occurred while trying to connect to the server" + e.toString());
} finally {
try {
if(out != null) {
out.close();
}
if(is != null) {
is.close();
}
} catch(IOException e) {
Log.e(TAG, "Error occurred while trying to close data streams" + e.toString());
}
}
}
Your question doesn't make sense. If there isn't a connection pool, there is no 'existing socket' to reuse.

Categories