how to view http post result in a browser using java - java

I would like to view the result of an http post in a browser but it is not working i've tried to use PrintWriter but still not showing the result in a browser
the system.out.println in the code is showing the result in the console i want the same result in the browser bellow is my code, i'm using netbeans and JSF
public void sendRequest() throws Exception{
String url = "http://34.198.239.23:3000/transactions";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", "Mozilla/5.0");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("secret_key", "afec6d477b7f4d91e177b707a4c58bf55b921926"));
urlParameters.add(new BasicNameValuePair("public_key", "c0b7372d96633b6414a7e7b7a53c996d3a63acfb"));
urlParameters.add(new BasicNameValuePair("product_name", "amagati"));
urlParameters.add(new BasicNameValuePair("product_unitid", "id"));
urlParameters.add(new BasicNameValuePair("product_type", "food"));
urlParameters.add(new BasicNameValuePair("error_url","vugapay.com/terms"));
urlParameters.add(new BasicNameValuePair("success_url","vugapay.com"));
urlParameters.add(new BasicNameValuePair("amount","5000"));
urlParameters.add(new BasicNameValuePair("extra_field","hello"));
urlParameters.add(new BasicNameValuePair("currency","usd"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// i tried to use this to view this so that it can appear in the browser
PrintWriter printwriter=response.getAllHeaders();
printwriter.print(result.toString());
System.out.println(result.toString());
System.out.println("Done!");
}

System.out.println method is to print into console, So you need to use HttpServletResponse to print your text into browser
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// your code here
response.setContentType("text/html");
response.getWriter().print(result);
}

Related

Response code 404 using apache commons

I'm building a wrapper for an API http://www.sptrans.com.br/desenvolvedores/APIOlhoVivo/Documentacao.aspx?1#docApi-autenticacao (it's in portuguese, but you get the idea).
I'm getting response code 404 when making a POST request and I have no idea why.
This is what is being printed:
Response Code : 404 {"Message":"No HTTP resource was found that
matches the request URI
'http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar'."}
public static String executePost() {
CloseableHttpClient client = HttpClientBuilder.create().build();
String targetURL = "http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar";
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("token","3de5ce998806e0c0750b1434e17454b6490ccf0a595f3884795da34460a7e7b3"));
try {
HttpPost post = new HttpPost(targetURL);
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) result.append(line);
System.out.println(result.toString());
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
It looks to me from the API documentation (albeit, I can't read Portugese), that the token needs to be in the URL, not POSTed to it:
POST /Login/Autenticar?token={token}
I think you are POSTing a form to this endpoint.
You should try this:
String targetURL = "http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar?token=3de5ce998806e0c0750b1434e17454b6490ccf0a595f3884795da34460a7e7b3";
And don't call post.setEntity(...).

How to get parameter on server from POST Url

I am trying to hit some URL using Post Method from client side with some data in the format of "NameValuePair", And receive that data from URL in servlet (server side) for performing some calculation and send back response to the client in JSON fromat.
But I am able to find correct data on Servlet (server)
Hit URL from Client Side
private void sendHTTPSPost() throws Exception {
String url = "http://localhost:8080/test/Registration";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("name", "A"));
urlParameters.add(new BasicNameValuePair("age", "12"));
urlParameters.add(new BasicNameValuePair("sex", "M"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
On Servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
System.out.println("Value of param is ------------------"+paramName);
String paramValue = request.getHeader(paramName);
System.out.println("Value of key is ------------------"+paramValue);
}
}
I tried a lot but not get correct result.
you are missing
post.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
You are getting the headers from the request you must use the request.getParameterNames() to get the parameters.
You can use -
requests.getParameter("name"); //returns A
requests.getParameter("age"); //returns 12
requests.getParameter("sex"); //returns M

download a file using apache http

I was trying to download a zip file from a page which requries username/password to access ( html form based authentication). I am using apache http library for it.
Earlier I had worked on something very similar, that page required just password to download the file.
Here is my code
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
public URI lastRedirectedUri;
public boolean isRedirected(HttpRequest request,
HttpResponse response,
HttpContext context) {
boolean isRedirect = false;
try {
isRedirect =
super.isRedirected(request, response,
context);
} catch (org.apache.http.ProtocolException e) {
e.printStackTrace();
}
if (!isRedirect) {
int responseCode =
response.getStatusLine().getStatusCode();
if (responseCode == 301 ||
responseCode == 302) {
System.out.println("the original response code is" + responseCode);
return true;
}
}
return isRedirect;
}
// public URI getLocationURI(HttpResponse response, HttpContext context)
// throws ProtocolException {
//
// lastRedirectedUri = super.getLocationURI(request , response, context);
//
// return lastRedirectedUri;
// }
});
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
// formparams.add(new BasicNameValuePair("password", arg[1]));
formparams.add(new BasicNameValuePair("password", "*****"));
formparams.add(new BasicNameValuePair("email", "****"));
UrlEncodedFormEntity entity1 =
new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost =
new HttpPost("https://*************************/l/?next=/s/48750/d/");
// new HttpPost(arg[0]);
httppost.setEntity(entity1);
HttpContext localContext = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
localContext.setAttribute(ClientContextConfigurer.COOKIE_STORE, cookieStore);
HttpResponse response = httpclient.execute(httppost, localContext);
HttpHost target =
(HttpHost)localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
System.out.println("Final target: " + target);
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
FileOutputStream fos =
new java.io.FileOutputStream("download.zip");
entity.writeTo(fos);
fos.close();
}
if you open the url provided in the code you will find the form has two parameters by the name email and password , and I have supplied them as formparams ( values commented in the code above ).
Any help will be greatly appreciated.
Try using BasicAuthentication.
http://hc.apache.org/httpclient-3.x/authentication.html#Authentication_Schemes
http://hc.apache.org/httpclient-3.x/authentication.html#Examples

Android c2dm server simulator on emulator

I am following android c2dm example from following link:
http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html
I have implemented the client side successfully and have got my registration id. but i am having some issues in server end using the same example actually the issue is in getAuthentification method and i am getting following exception at HttpResponse response = client.execute(post).
java.net.UnknownHostException: www.google.com
Following is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email","you....#gmail.com"));
nameValuePairs.add(new BasicNameValuePair("Passwd","*********"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
Editor edit = prefManager.edit();
edit.putString(AUTH, line.substring(5));
edit.commit();
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
Please help me? Your help would be highly appreciable. Thanks,
I had this exact same issue last week. When the C2DM servers return a 302 Moved (www.google.com) what they ACTUALLY mean is the authentication failed. The problem is almost certainly your authentication code, so re-check the code you're using to get the auth code from the ClientLogin API. Note that the HTTP response contains a bunch of information, not just the auth code, so you do need to parse it correctly (that was my mistake).
public static String getClientLoginAuthToken(String email, String password) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", email));
nameValuePairs.add(new BasicNameValuePair("Passwd", password));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source","Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
if (line.startsWith("Auth=")) {
return line.substring(5);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG, "Failed to get C2DM auth code");
return "";
}

Programmatically logging in from WebView

In my Android application I'm using a web view to access some web mapping data provided by a server. The server requires some HTTP form based authentication to allow access to those data. Due to the fact that the site doesn't have a mobile version, displaying the login page (or any other pages) looks pretty bad . Unfortunately the site is hardly into my reach so I've thought of the following approach:
use a native user interface to collect the username and password
thought a Http post send those information to the server
after the response is received get the cookies the server is sending
set the cookies to the the web view
try to finally access the desired data
For now I'm just trying to pass the login phase.
Is this a viable solution , or is just plain wrong and I should try something else ?
For completeness I post the code below
A. The authentication part
private String authenticate() throws Exception
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mySite/login_form");
HttpResponse response = null;
BufferedReader in = null;
String resultContent = null;
try
{
// Add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("came_from", ""));
nameValuePairs.add(new BasicNameValuePair("form.submitted", "1"));
nameValuePairs.add(new BasicNameValuePair("js_enabled", "0"));
nameValuePairs.add(new BasicNameValuePair("cookies_enabled", ""));
nameValuePairs.add(new BasicNameValuePair("login_name", ""));
nameValuePairs.add(new BasicNameValuePair("pwd_empty", "0"));
nameValuePairs.add(new BasicNameValuePair("name", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// Execute HTTP Post Request
response = httpclient.execute(httppost,localContext);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
resultContent = sb.toString();
Log.i("mytag","result :"+resultContent);
cookies = new java.util.ArrayList();
cookies = cookieStore.getCookies();
}
catch (ClientProtocolException e)
{
Log.i("mytag","Client protocol exception");
}
catch (IOException e)
{
Log.i("mytag","IOException");
}
catch(Exception e)
{
Log.i("mytag","Exception");
Log.i("mytag",e.toString());
}
return resultContent;
}
B. Setting the cookies and loading the desired page
private void init()
{
CookieSyncManager.createInstance(this);
CookieManager cookieMan= CookieManager.getInstance();
cookieMan.setAcceptCookie(true);
cookies = StartupActivity.listAfter;
if(cookies != null)
{
for (int i = 0; i<cookies.size(); i++)
{
Cookie cookie = cookies.get(i);
cookieMan.setCookie("cookie.getDomain()",cookie.getValue());
}
}
CookieSyncManager.getInstance().sync();
webView = (WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new HelloWebViewClient());
}
protected void onResume()
{
super.onResume();
// test if the we logged in
webView.loadUrl("mySite/myDesiredFeature");
}
The results of loading that page is that the login_page form is displayed
1) Try first to make HttpGet request, to get cookies, then perform HttpPost. I think this way you should not add cookies manually.
Use one HttpClient to do this.
2) Instead of
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
resultContent = sb.toString();
use
EntityUtils.toString(response.getEntity()).

Categories