How to get HTTP response code for a URL in Java? - java

Please tell me the steps or code to get the response code of a particular URL.

HttpURLConnection:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.
If you need something with more capability, check out HttpClient.

URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();

You could try the following:
class ResponseCodeCheck
{
public static void main (String args[]) throws Exception
{
URL url = new URL("http://google.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
System.out.println("Response code of the object is "+code);
if (code==200)
{
System.out.println("OK");
}
}
}

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
public class API{
public static void main(String args[]) throws IOException
{
URL url = new URL("http://www.google.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
System.out.println(statusCode);
}
}

This has worked for me :
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
//args[0] ="http://hostname:port/xyz/zbc";
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
int code = response1.getStatusLine().getStatusCode();
try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
// Read in all of the post results into a String.
String output = "";
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println("Response-->"+output);
}
catch(Exception e){
System.out.println("Exception"+e);
}
}

This is what worked for me:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlHelpers {
public static int getHTTPResponseStatusCode(String u) throws IOException {
URL url = new URL(u);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
return http.getResponseCode();
}
}
Hope this helps someone :)

Efficient way to get data(With uneven payload) by scanner.
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A"); // Put entire content to next token string, Converts utf8 to 16, Handles buffering for different width packets
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}

Try this piece of code which is checking the 400 error messages
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode >= 400) {
System.out.println(url+" is a broken link");
} else {
System.out.println(url+" is a valid link");
}

This is the full static method, which you can adapt to set waiting time and error code when IOException happens:
public static int getResponseCode(String address) {
return getResponseCode(address, 404);
}
public static int getResponseCode(String address, int defaultValue) {
try {
//Logger.getLogger(WebOperations.class.getName()).info("Fetching response code at " + address);
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(1000 * 5); //wait 5 seconds the most
connection.setReadTimeout(1000 * 5);
connection.setRequestProperty("User-Agent", "Your Robot Name");
int responseCode = connection.getResponseCode();
connection.disconnect();
return responseCode;
} catch (IOException ex) {
Logger.getLogger(WebOperations.class.getName()).log(Level.INFO, "Exception at {0} {1}", new Object[]{address, ex.toString()});
return defaultValue;
}
}

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
.
.
.
.
.
.
.
System.out.println("Value" + connection.getResponseCode());
System.out.println(connection.getResponseMessage());
System.out.println("content"+connection.getContent());

you can use java http/https url connection to get the response code from the website and other information as well here is a sample code.
try {
url = new URL("https://www.google.com"); // create url object for the given string
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(https_url.startsWith("https")){
connection = (HttpsURLConnection) url.openConnection();
}
((HttpURLConnection) connection).setRequestMethod("HEAD");
connection.setConnectTimeout(50000); //set the timeout
connection.connect(); //connect
String responseMessage = connection.getResponseMessage(); //here you get the response message
responseCode = connection.getResponseCode(); //this is http response code
System.out.println(obj.getUrl()+" is up. Response Code : " + responseMessage);
connection.disconnect();`
}catch(Exception e){
e.printStackTrace();
}

Its a old question, but lets to show in the REST way (JAX-RS):
import java.util.Arrays;
import javax.ws.rs.*
(...)
Response response = client
.target( url )
.request()
.get();
// Looking if response is "200", "201" or "202", for example:
if( Arrays.asList( Status.OK, Status.CREATED, Status.ACCEPTED ).contains( response.getStatusInfo() ) ) {
// lets something...
}
(...)

Related

How to send post request in java with a JSON body

I am confused as to how to send a post request in Java with JSON parameters. I have seen many examples that use HttpPost library which I can not access. Below is my code:
public class endpointtest {
public String endpoint(String urlStr, String username) {
final StringBuilder response = new StringBuilder();
try {
//creating the connection
URL url = new URL(urlStr);
HttpClient client = HttpClient.newHttpClient();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
//builds the post body, adds parameters
final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//out.writeBytes(toJSON(globalId));
out.flush();
out.close();
//Reading the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputline;
while ((inputline = in.readLine()) != null) {
response.append(inputline);
}
in.close();
connection.getResponseCode();
connection.disconnect();
} catch (final Exception ex) {
ex.printStackTrace();
System.out.println(" error ");
}
return response.toString();
}
}
class main {
public static void main(String[] args){
endpointtest ep = new endpointtest();
ep.endpoint("localhost:8080/endpoint","""
{
"name": "mike",
"Id": "123"
}
""");
}
}
I am trying to pass the json in the main method (I know I am not doing it right), and was wondering as to how I would do this correctly.
This is the simplest way to do it.
public class Main {
public static void main(String[] args) throws IOException {
String apiUrl = "http://myserver/rest/V1.0/manage/export"; // Your api/http link
String userName = "admin"; // Your username
String password = "adminpro"; // Your password
sendRequest(basicUrl, userName, password);
}
public static void sendRequest(String apiurl,String userName,String password){
try{
URL url = new URL(apiurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes()));
String payload = "{\"sampleKey\":\"sampleValue\"}";// This should be your json body i.e. {"Name" : "Mohsin"}
byte[] out = payload.getBytes(StandardCharsets.UTF_8);
OutputStream stream = connection.getOutputStream();
stream.write(out);
System.out.println(connection.getResponseCode() + " " + connection.getResponseMessage()); // THis is optional
connection.disconnect();
}catch (Exception e){
System.out.println(e);
System.out.println("Failed successfully");
}
}
}
This Question is asked before here:
HTTP POST using JSON in Java
See it and comment this if you face any problem.

Server returned HTTP response code: 401 for url when using shopify API

My url as given by the shopify is in this format
https://apikey:password#hostname/admin/orders.json
So when trying to get the orders using HttpURLConnection, I am getting 401 unauthorised error. Here is my code
import java.io.*;
import java.net.*;
import java.util.Properties;
/**
* Created by admin on 22/8/15.
*/
public class Hello {
// This method should be removed in production
static void setProxy(){
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost","lotus");
systemProperties.setProperty("http.proxyPort", "8080");
}
public static void main(String [] args)
{
try
{
setProxy();
URL url = new URL("https://apikey:password#go-frugal.myshopify.com/admin/orders.json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent","Mozilla/5.0");
connection.setRequestProperty("Content-Type","application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Here is the error
java.io.IOException: Server returned HTTP response code: 401 for URL: https://apikey:password#go-frugal.myshopify.com/admin/orders.json
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1313)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at Hello.main(Hello.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 0<br>
getErrorStream returns this
{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
try this ... your call sequence is wrong. hope this help.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.jboss.util.Base64;
public class test9 {
public static void main(String[] args) {
URL url;
URLConnection urlConn = null;
HttpURLConnection htcon = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
String authStr = "apikey:password";
String authStringEnc = Base64.encodeBytes(authStr.getBytes());
//String authStringEnc = new String(Base64Encoder.encode(authString.getBytes()));
try {
url = new URL("https:go-frugal.myshopify.com/admin/orders.json");
urlConn = url.openConnection();
urlConn.setRequestProperty("Authorization", "Basic " + authStringEnc);
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("user-agent","Mozilla/5.0");
urlConn.setRequestProperty("Content-Type","application/json");
htcon = (HttpURLConnection) urlConn;
is = htcon.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
System.out.println("sb: "+sb);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is an oversight in the way Java handles authorization at the connection level. Took me a good long time to debug; it works in the browser, so why doesn't it work in Java?
Turns out that web browsers will automatically encode the authorization token for any URLs with a user info space. Java doesn't do this by default, so you have to do it yourself:
URI uri = new URL("http://username:password#protected.domain.example/resource").toURI();
String userInfo = uri.getRawUserInfo();
if(userInfo != null && userInfo.length() > 0)
userInfo = Base64.getEncoder().encodeToString(userInfo.getBytes());
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
if(userInfo != null && userInfo.length() > 0)
connection.setRequestProperty("Authorization", "Basic " + userInfo);
connection.connect();
A few notes:
You can try using URL#getUserInfo() or URI#getUserInfo(), but there's a small chance that it won't encode passwords with legal special characters correctly.
This should work for all HTTP URLs, even if they don't have a user info segment.

Java automatic-login to website. Does not work

I want to create a java application that automatically logs into a website and does stuff. I'm testing it on my localhost. I'm actually totally new at this and I'm trying to get the concept from http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/ and modifying the code to actually work for my localhost.
package random;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class InternetAutomationPost {
List<String> cookies;
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
public List<String> getCookies() {
return cookies;
}
private String requestWebPage(String address) {
try {
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// Don't use cache. Get a fresh copy.
con.setUseCaches(false);
// Use post or get.
// And default is get.
con.setRequestMethod("GET");
// Mimic a web browser.
con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Connection", "keep-alive");
con.addRequestProperty("User-Agent", "Mozilla/5.0");
if(cookies != null) {
con.addRequestProperty("Cache-Control", "max-age=0");
for (String cookie : this.cookies) {
System.out.print(cookie.split(";", 1)[0]);
con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while( (inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
// Get the response cookies
setCookies(con.getHeaderFields().get("Set-Cookie"));
return response.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private String parsePage(String page) {
Document doc;
try {
doc = Jsoup.parse(page);
Elements form = doc.getElementsByAttributeValue("action", "login.php");
List<String> paramList = new ArrayList<String>();
for(Element loginForm : form) {
System.out.println(loginForm.html());
Elements Input = loginForm.getElementsByTag("input");
for(Element input : Input) {
String name = input.attr("name");
String value = input.attr("value");
if(name.equals("email")) {
value = "admin#admin.com";
} else if(name.equals("password")) {
value = "password";
} else if(name.equals("")) {
continue;
}
paramList.add(name + "=" + URLEncoder.encode(value, "UTF-8"));
}
}
StringBuilder params = new StringBuilder();
for(String values : paramList) {
if(params.length() == 0) {
params.append(values);
} else {
params.append("&" + values);
}
}
System.out.println("Params: " + params);
return params.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private void sendPostLogin(String location, String params) {
try {
URL url = new URL(location);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Don't use cache. Get a fresh copy.
con.setUseCaches(false);
// Use post or get. We use post this time.
con.setRequestMethod("POST");
// Mimic a web browser.
con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Connection", "keep-alive");
con.addRequestProperty("User-Agent", "Mozilla/5.0");
if(cookies != null) {
con.addRequestProperty("Cache-Control", "max-age=0");
for (String cookie : this.cookies) {
con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
con.addRequestProperty("Content-Length", Integer.toString(params.length()));
con.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.addRequestProperty("Host", "localhost");
con.addRequestProperty("Origin", "http://localhost");
con.addRequestProperty("Referrer", "http://localhost/social/index.php");
con.setDoOutput(true);
con.setDoInput(true);
// Write the parameters. Send post request.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while( (inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
// Get the response cookies
setCookies(con.getHeaderFields().get("Set-Cookie"));
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
InternetAutomationPost object = new InternetAutomationPost();
String page = object.requestWebPage("http://localhost/social");
String params = object.parsePage(page);
object.sendPostLogin("http://localhost/social/index.php", params);
}
}
EDIT:
Found out why it sent HTTP response code: 413.
con.addRequestProperty("Content-Length:", Integer.toString(params.length()));
should have been:
con.addRequestProperty("Content-Length", Integer.toString(params.length()));
There was a stray ':'. I've fixed it now.
BUT, still my code doesn't actually login and I still need help .
I have put my full program here now.
I might be wrong but I'm thinking that the params aren't actually getting written to the con.getOutputStream() in the code here:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
You set the Content-Length to Integer.toString(params.length())
My guess would be, that your params written as bytes are longer than the Content-Length and your server receives more bytes than expected.
Try:
con.addRequestProperty("Content-Length:", Integer.toString(params.getBytes("UTF-8").length()));
This depends on your encoding obviously. Also have a look at this.

Invoking servlet from java main method

import java.net.*;
import java.io.*;
public class sample
{
public static void main (String args[])
{
String line;
try
{
URL url = new URL( "http://localhost:8080/WeighPro/CommPortSample" );
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
line = in.readLine();
System.out.println( line );
in.close();
}
catch (Exception e)
{
System.out.println("Hello Project::"+e.getMessage());
}
}
}
My Servlet is invoking another Jsp page like the below,
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
I am not getting any reaction/output in the browser, where the servlet has to be executed once it is invoked.
Am I missing any basic step for this process? Please Help!!!
If you want to open it in browser try this
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://localhost:8080/WeighPro/CommPortSample"));
You question is not clear. Do you actually want to invoke a Servlet from the Main method, or do you want to make an HTTP request to your web application?
If you want to make an HTTP request, I can't see any obvious problems with your code above, which makes me believe that the problem is in the Servlet. You also mention that you don't get anything in the browser, but running your program above does not involve a browser.
Do you mean that you don't get a response when you go to
http://localhost:8080/WeighPro/CommPortSample
in a browser?
As Suresh says, you cannot call a Servlet directly from a main method.
Your Servlet should instead call methods on other classes, and those other classes should be callable from the main method, or from Test Cases. You need to architect your application to make that possible.
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class OutBoundSimul {
public static void main(String[] args) {
sendReq();
}
public static void sendReq() {
String urlString = "http://ip:port/applicationname/servletname";
String respXml = text;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter out = null;
BufferedInputStream inputStream = null;
try {
System.out.println("URL:"+urlString);
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
System.out.println("SendindData");
out = new OutputStreamWriter(urlConnection.getOutputStream());
System.out.println("Out:"+out);
out.write(respXml);
out.flush();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
int character = -1;
StringBuffer sb = new StringBuffer();
while ((character = inputStream.read()) != -1) {
sb.append((char) character);
}
System.out.println("Resp:"+sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Invoking Servlet with query parameters Form Main method
Java IO
public static String accessResource_JAVA_IO(String httpMethod, String targetURL, String urlParameters) {
HttpURLConnection con = null;
BufferedReader responseStream = null;
try {
if (httpMethod.equalsIgnoreCase("GET")) {
URL url = new URL( targetURL+"?"+urlParameters );
responseStream = new BufferedReader(new InputStreamReader( url.openStream() ));
}else if (httpMethod.equalsIgnoreCase("POST")) {
con = (HttpURLConnection) new URL(targetURL).openConnection();
// inform the connection that we will send output and accept input
con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST");
con.setUseCaches(false); // Don't use a cached version of URL connection.
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
DataOutputStream requestStream = new DataOutputStream ( con.getOutputStream() );
requestStream.writeBytes(urlParameters);
requestStream.close();
responseStream = new BufferedReader(new InputStreamReader( con.getInputStream(), "UTF-8" ));
}
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
while((line = responseStream.readLine()) != null) {
response.append(line).append('\r');
}
responseStream.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace(); return null;
} finally {
if(con != null) con.disconnect();
}
}
Apache Commons using commons-~.jar
{httpclient, logging}
public static String accessResource_Appache_commons(String url){
String response_String = null;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod( url );
// PostMethod method = new PostMethod( url );
method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
method.setQueryString(new NameValuePair[] {
new NameValuePair("param1","value1"),
new NameValuePair("param2","value2")
}); //The pairs are encoded as UTF-8 characters.
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
//Get data as a String OR BYTE array method.getResponseBody()
response_String = method.getResponseBodyAsString();
method.releaseConnection();
} catch(IOException e) {
e.printStackTrace();
}
return response_String;
}
Apache using httpclient.jar
public static String accessResource_Appache(String url) throws ClientProtocolException, IOException{
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder( url )
.addParameter("param1", "appache1")
.addParameter("param2", "appache2");
HttpGet method = new HttpGet( builder.build() );
// HttpPost method = new HttpPost( builder.build() );
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse( final HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return "";
}
};
return httpclient.execute( method, responseHandler );
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
JERSY using JARS {client, core, server}
public static String accessResource_JERSY( String url ){
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource( url );
ClientResponse response = service.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
if (response.getStatus() != 200) {
System.out.println("GET request failed >> "+ response.getStatus());
}else{
String str = response.getEntity(String.class);
if(str != null && !str.equalsIgnoreCase("null") && !"".equals(str)){
return str;
}
}
return "";
}
Java Main method
public static void main(String[] args) throws IOException {
String targetURL = "http://localhost:8080/ServletApplication/sample";
String urlParameters = "param1=value11&param2=value12";
String response = "";
// java.awt.Desktop.getDesktop().browse(java.net.URI.create( targetURL+"?"+urlParameters ));
// response = accessResource_JAVA_IO( "POST", targetURL, urlParameters );
// response = accessResource_Appache_commons( targetURL );
// response = accessResource_Appache( targetURL );
response = accessResource_JERSY( targetURL+"?"+urlParameters );
System.out.println("Response:"+response);
}
Simply you cannot do that.
A response and request pair will generated by web container. You cannot generate a response object and send to the browser.
By the way which client/browser you are expecting to get the response ? No idea. Right ?
When container receives a request from client then it generates response object and serves you can access that response in service method.
If you want to see/test the response, you have to request from there.

Java: how to use UrlConnection to post request with authorization?

I would like to generate POST request to a server which requires authentication. I tried to use the following method:
private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
String data = "product[title]=" + URLEncoder.encode(title) +
"&product[content]=" + URLEncoder.encode(content) +
"&product[price]=" + URLEncoder.encode(price.toString()) +
"&tags=" + tags;
try {
URL url = new URL(urlString);
URLConnection conn;
conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
return rd.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
and the line
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
also throws an IOException.
Anyway I would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using POST with UrlConnection.
but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection to HttpURLConnection, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
I don't see anywhere in the code where you specify that this is a POST request. Then again, you need a java.net.HttpURLConnection to do that.
In fact, I highly recommend using HttpURLConnection instead of URLConnection, with conn.setRequestMethod("POST"); and see if it still gives you problems.
To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me
Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback
BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work.
Inside my servlet to do GET using url like
e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked
Thanks to all contributors
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
To send a POST request call:
connection.setDoOutput(true); // Triggers POST.
If you want to sent text in the request use:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
wr.write(textToSend);
wr.flush();
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
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());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
and Just call the function when you needed to get the data from server either by post or get like this
HashMap<String, String>params = new HashMap<String, String>();
params.put("action", "request_sample");
params.put("name", uname);
params.put("message", umsg);
params.put("email", getEmailofUser());
params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
#Override
public void onSucess(Bundle bundle) {
debug("data", bundle.getString(DbConstants.RESPONSE));
}
#Override
public void onFailed(int status_code, String mesage, String url) {
debug("sample", mesage);
}
});
Now it is complete.Enjoy!!! Comment it if find any problem.
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
i was looking information about how to do a POST request. I need to specify that mi request is a POST request because, i'm working with RESTful web services that only uses POST methods, and if the request isn't post, when i try to do the request i receive an HTTP error 405. I assure that my code isn't wrong doing the next: I create a method in my web service that is called through GET request and i point my application to consume that web service method and it works.
My code is the next:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());

Categories

Resources