I use Robotium to test Android app. In the middle of a test I need to create POST request to server to some money to user and then verify that changes are reflected in UI.
Request looks like:
wwww.testserver.com/userAddMoney?user_id=1&amount=999
But to authorize on server I need to pass special parameters to Header of request:
Headers: X-Testing-Auth-Secret: kI7wGju76kjhJHGklk76
You could look into the Apache HC package:
HttpPost post = new HttpPost( "http://wwww.testserver.com/userAddMoney" );
...
post.addHeader( "X-Testing-Auth-Secret" , "kI7wGju76kjhJHGklk76" );
...
Cheers,
Related
I am trying to use a web API in a Java program using Apache HttpClient5.
Using a simple request with curl:
curl -X POST -H "x-api-user: d904bd62-da08-416b-a816-ba797c9ee265" -H "x-api-key: xxxxxxxxxxx" https://habitica.com/api/v3/user/class/cast/valorousPresence
I get the expected response and effect.
Using my Java code:
URI uri = new URIBuilder()
.setScheme("https")
.setHost("habitica.com")
.setPath("/api/v3/user/class/cast/valorousPresence")
.build();
Logger logger = LoggerFactory.getLogger(MyClass.class);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(new BasicHeader("x-api-user",getApiUser()));
httpPost.addHeader(new BasicHeader("x-api-key", getApiKey()));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
logger.info(httpResponse.toString());
return httpResponse.getCode();
The output I get when running the Java call is
411 Length Required HTTP/1.0
I'm sure I'm not constructing the POST call correctly, how should it be done? I've tried specifying Content-Type and that has no effect. Trying to set Content-Length in the code causes compilation errors (as I understand it, this is handled behind the scenes by HttpClient5).
All my GET requests using HttpClient5 work fine.
A POST always has a payload (content). A POST without content is unusual, so are you sure you didn't forget something?
You need to call setEntity() to set the payload, even if it is empty, because it is the entity that sets the Content-Length header.
E.g. you could call httpPost.setEntity(new StringEntity("")), which sets Content-Type: text/plain and Content-Length: 0.
I've created a Java adapter which accepts Multipart Form data. Now I want to create a multipart request from my native Android App. But I'm not able to figure out how to construct a multipart request using WLResourceRequest class in MobileFirst API. Any example or pointer in this direction will be greatly appreciated.
Thanks in advance!
You needn't do this via WLResourceRequest in the client-side.
IMO what you should do is something similar to this:
// Create the request to send
final HttpPost post = new HttpPost("your-destination");
// Construct the body of the object...
...
...
// Send the request and get the response
HttpResponse response = client.execute(post);
If you have security involved, you may want to read the following documentation as well (think POST instead of GET): http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.0.0/com.ibm.worklight.dev.doc/dev/c_custom_request_to_resource_java.html?lang=en
I am using Apache HTTP Client Library to send HTTP request. I have following questions:
1- Does this library attaches any default headers to the request, or you have to attach all the headers yourself.
HttpClient client = new HttpClient();;
HttGet request = new HttpGet('http://www.example.com');
//Now Can i execute the request directly or do i need to
//add headers before executing the request
client.execute(request);
2- I also want to see the headers that are being sent to the server. I tried "request.getHeaders()" but it just prints - "[Lorg.apache.http.Header;#1bc2616". How can I get it to print headers in a name - value format.
What version of Apache HttpClient are you using? In version 4.0.1 there is a method HttpGet#getAllHeaders() which returns an array of Header object. See grep code here - http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpcore/4.0.1/org/apache/http/message/AbstractHttpMessage.java#AbstractHttpMessage.getAllHeaders%28%29
I tried running this code:
final HttpClient client = new DefaultHttpClient();
final HttpGet get = new HttpGet("http://www.google.com");
client.execute(get);
for (final Header header : get.getAllHeaders()) {
System.out.println("Header: " + header.getName() + " = " + header.getValue());
}
System.out.println(get.getAllHeaders().length);
I did not see any headers getting printed in the console and get.getAllHeaders().length returned zero (0). So I would assume that HttpClient doesn't provide any default Headers.
I wouldn't recommend to use separate HttpGet/HttpPost/HttpPut
but HttpRequest Interface. There you'll be able to set Header/body as HttpEntity.
But Default header is attached:
method: GET/POST/PUT by default;
You should separately set Content-Type and Encoding
I'm new to OAuth and trying to send a https GET request to retrieve something. Earlier I was using POSTMAN to test that and I was able to execute the GET request with OAUth 1.0 header authorization. The header authorization looks something as
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxxxxxxx" ,oauth_signature_method="HMAC-SHA1" ,oauth_timestamp="1409861973" ,oauth_nonce="x1409861973681" ,oauth_version="1.0" ,oauth_signature="M+Dq62XboEd3+t6VDIcLy86zlQg="
The query looks something as
https://secure.api.abc.net/DataService/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,yyyyy}
Note that I'm able to execute this fine from POSTMAN.
Now, I need to code that in java and I'm able to generate the oauth signature fine, but I'm wondering how do I set the authorization header after that in a https request???
Please advise as I'm new to oauth and want to learn.
I guess if your doing in Java, you will need to use the Apache HttpClient or something similar to make that request to the server and set the OAuth header to the request.
Code sample using the Apache HttpClient below.
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("OAuth", oauthHeaderString);
HttpResponse response = client.execute(request);
is it possible to pass some data in HTTP Header, while redirecting a request from one server to another.
Here is my scenario,
I have one generic filter, via which every request is passing.
Now, based on some condition, I'm redirecting the request to some different server using the API objHttpServletResponse.sendRedirect(strURL).
But, the issue is, when I'm setting some data in response header like objHttpServletResponse.setHeader("Key", "Value"); That's not available in the redirected server.
So, my questions are,
1. Is there any way to pass some data in header while redirecting a request?
2. If not, what are the other possible ways to send some data while redirecting a request?
Please Note: few other ways, like
using URL parameters:
objHttpServletResponse.sendRedirect(strURL+"?param="+ strParamValue);
or
using session:
HttpSession session = httpRequest.getSession();
session.setAttribute("Key", "Value");
is not what I'm expecting.
The headers you set are written to the response that gets sent to the client, along with a Location header and a status code. See Redirecting a request using servlets and the "setHeader" method not working
The client is then supposed to send an identical request to the URL you specified in the Location header. Identical to the request it sent to you.
You want the browser to send a header you specify along with the redirected request. Have you considered adding a (domain) Cookie header? Some googling leads me to believe that cookies set in a redirect response will get picked up by most browsers. See http://blog.dubbelboer.com/2012/11/25/302-cookie.html
Please have a look at Apache HttpClient.
This example adds several parameters to the post request :
String url = "https://selfsolve.apple.com/wcResults.do";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("cn", ""));
urlParameters.add(new BasicNameValuePair("locale", ""));
urlParameters.add(new BasicNameValuePair("caller", ""));
urlParameters.add(new BasicNameValuePair("num", "12345"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
The problem is that the redirect() method of the response initiates a new request altogether, thereby loosing the attributes that were set before redirecting. Luckily there is a fluent way of solving the problem still.
response.setHeader("Key", "Value");
request.getRequestDispatcher("redirecturl").forward(request, response);
Then in your destination you can do
response.getHeaders("key")
You can use JS redirect, i.e. instead of calling sendRedirect return HTML page with embedded javascript that will do redirect setting headers you need.
However, using GET parameters is really the best solution. If you have concerns about users altering parameters manually - use MAC code to protect parameters.See
Message authentication code
In simplest form, ?p1=1&p2=2&mac={mac value}, where {mac value} = md5('MY_SECRET_KEY' + 'p1=1&p2=2').
Receiving side can recalculate MAC and compare it with provided one. Since external users can not know 'MY_SECRET_KEY', they will not be able to make valid MAC.
Have you checked the HTTP request/response from/to server? You can use a number of plugins on chrome or firefox to check that. You would be able to see if value is being passed from your server to another server or not
Also retrieve the header using httpResponse.getHeader("Key"); not using request.getHeader("key"). One of my colleague was facing same issue some days back, he was using request to fetch header values