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
Related
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);
}
I am trying to hit the Liferay logout servlet "c/portal/logout" through Java, but it always returns a 400 response:
private void sendPost() throws Exception {
String url = "localhost:8080/c/portal/logout";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
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());
}
Assuming your intention is to logout a user's session, the best way is to call sendRedirect on an HttpServletResponse reference
public void myPostAction(ActionRequest request, ActionResponse response) throws Exception {
// ...
response.sendRedirect("/c/portal/logout");
}
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(...).
I'm trying to post a comment from desktop application to Trac.
I'm using apache http client library in this project here is a link
Here is my code, sorry if it's hard to read
public class TestComment {
private static String cookie;
public static void main(String[] args) throws Exception {
CookieHandler.setDefault(new CookieManager());
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:8080/mytrac/login");
BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + encodedPassword("admin", "123123"));
httpGet.addHeader(authHeader);
HttpResponse response = defaultHttpClient.execute(httpGet);
List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies();
String token = null;
if(!cookies.isEmpty()){
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
token = cookies.get(i).toString().substring(43, 67);
System.out.println(token);
}
}
setCookie(token);
responseLog(response);
HttpPost httpPost = new HttpPost("http://localhost:8080/mytrac/ticket/2#comment:5");
httpPost.setHeader(authHeader);
httpPost.setHeader("Host", "localhost:8080");
httpPost.setHeader("User-Agent", "Mozilla/5.0");
httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-US,en;q=0.8");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Referer", "http://localhost:8080/mytrac/ticket/2");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("__FORM_TOKEN", token));
formparams.add(new BasicNameValuePair("comment", "Test comment"));
formparams.add(new BasicNameValuePair("field_reporter", "admin"));
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
response = defaultHttpClient.execute(httpPost);
responseLog(response);
System.out.println(response.getStatusLine());
}
private static String encodedPassword(String username, String password) {
byte[] encodedPassword = (username + ":" + password).getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(encodedPassword);
}
private static void responseLog(org.apache.http.HttpResponse httpResponse) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse. getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer();
String line1;
while ((line1 = bufferedReader.readLine()) != null) {
stringBuffer.append(line1 + "\n");
}
System.out.println(stringBuffer) ;
}
public static String getCookie() {
cookie = cookie.substring(cookie.indexOf(":") + 1);
return cookie;
}
public static void setCookie(String cookie) {
TestComment.cookie = cookie;
}
}
When I run this code I get 200 code it tells ok and I even get my comment in Text-Aria form, but don't post it. When I post a comment in browser the code is 303. Where am I wrong, may be I am on totaly wrong way?
We resolved the problem
I didn't know but i just needed to send one more form, we need to get view time from trac and send it as a form:
formparams.add(new BasicNameValuePair("view_time", view_time));
now it works
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()).