I try to pass parameters in post request in integration test, but I get response that required parameter "source" aint detected. Maybe you will know what is cause. Thank you.
public void testUploadBundleFromRepository() throws IOException, InterruptedException {
String boundary = "---------------"+ UUID.randomUUID().toString();
String uri = String.format("http://%s:%d/upload/", HOST, PORT);
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.MULTIPART_FORM_DATA.getMimeType()+";boundary="+boundary);
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("source","repo"));
postParameters.add(new BasicNameValuePair("id","1"));
postParameters.add(new BasicNameValuePair("start", "true"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
HttpResponse response = getHttpClient().execute(httpPost);
//assert in future
}
I think you should call setRequestBody not setEntity
httpPost.setRequestBody(postParameters);
Related
I need to replicate a Postman POST in Java.
Usually I had to make an HttpPost with only params in URL, so it was easy to build:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
But what I have to do if I have a POST like the image below where there are Params in URL and Body TOGETHER??
Now I'm making the HttpPost like this:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("someUrls.com/upload");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("owner", owner));
postParameters.add(new BasicNameValuePair("destination", destination));
try{
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
HttpResponse httpResponse = client.execute(post);
//Do something
}catch (Exception e){
//Do something
}
But how I put "filename" and "filedata" params in the Body together with the params in the URL?
Actually I'm using org.Apache library, but i could consider also others library.
Thanks to anybody that will help!
You can use below code to pass the body parameters as "application/x-www-form-urlencoded" in POST method call
package han.code.development;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpPost
{
public String getDatafromPost()
{
BufferedReader br=null;
String outputData;
try
{
String urlString="https://www.google.com"; //you can replace that with your URL
URL url=new URL(urlString);
HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Authorization", "Replace with your token"); // if you have any accessToken to authorization, just replace
connection.setDoOutput(true);
String data="filename=file1&filedata=asdf1234qwer6789";
PrintWriter out;
if((data!=null))
{
out = new PrintWriter(connection.getOutputStream());
out.println(data);
out.close();
}
System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb=new StringBuilder();
String str=br.readLine();
while(str!=null)
{
sb.append(str);
str=br.readLine();
}
outputData=sb.toString();
return outputData;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
HttpPost post=new HttpPost();
System.out.println(post.getDatafromPost());
}
}
I think this question, and this question are about similar issues and both have good answers.
I would recommend using this library as it is well maintained and simple to use if you want.
I've resolved making this way:
put on POST URL header params;
adding as MultipartEntity the filename and filedata.
Here the code....
private boolean uploadQueue(String username, String password, String filename, byte[] fileData)
{
HttpClient client = HttpClientBuilder.create().build();
String URL = "http://post.here.com:8080/";
HttpPost post = new HttpPost(URL +"?username="+username+"&password="password);
try
{
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addBinaryBody("filedata", fileData, ContentType.DEFAULT_BINARY, filename);
entityBuilder.addTextBody("filename", filename);
post.setEntity(entityBuilder.build());
HttpResponse httpResponse = client.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
logger.info(EntityUtils.toString(httpResponse.getEntity()));
return true;
}
else
{
logger.info(EntityUtils.toString(httpResponse.getEntity()));
return false;
}
}
catch (Exception e)
{
logger.error("Error during Updload Queue phase:"+e.getMessage());
}
return false;
}
I'm trying to to submit a form, but before this form I have to log in, so I should do 2 posts in a line, somebody has any idea in how to do that, there is what I have here:
// Making HTTP request
try {
String redirectedUrl = getUrl(url);
// defaultHttpClient
HttpPost httpPost = new HttpPost(redirectedUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", login));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
The problem there is that when I log in, it just retrieve a response and I can't do anything with, I need to post inside the resource that is protected, somebody has any idea about what I should do. The getUrl function is shown below:
private String getUrl(String url) throws ClientProtocolException, IOException {
HttpGet httpget = new HttpGet(url);
HttpContext context = new BasicHttpContext();
HttpResponse response = httpClient.execute(httpget, context);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(response.getStatusLine().toString());
HttpUriRequest currentReq = (HttpUriRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
return (currentReq.getURI().isAbsolute()) ? currentReq
.getURI().toString() : (currentHost.toURI() + currentReq
.getURI());
}
private static CookieStore cookieStore = new BasicCookieStore();
private HttpClient client = new DefaultHttpClient();
private static HttpContext httpContext = new BasicHttpContext();
public static void main(String[] args) throws Exception {
String url = "http://www.codechef.com";
String account = "http://www.codechef.com/node?destination=node";
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
List<NameValuePair> postParams = http.getFormParams();
sendPost(url, postParams);
}
private void sendPost(String url, List<NameValuePair> postParams)
throws Exception {
HttpPost post = new HttpPost(url);
post.setHeader("Accept","text/plain");
post.setHeader("Accept-Language", "en-US");
post.setHeader("Connection", "keep-alive");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post,httpContext);
List<Cookie> cook=cookieStore.getCookies();
if(cook==null)
System.out.println("Null");
else{
System.out.println(cook.size());
for(Cookie c:cook){
String cookieReader=c.getName()+" = "+c.getValue()+";domain= "+c.getDomain();
System.out.println(cookieReader);
}
}
}
public List<NameValuePair> getFormParams() throws UnsupportedEncodingException {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("name","name"));
paramList.add(new BasicNameValuePair("pass","pass"));
return paramList;
}
After the post method, the size of the cookie is 0, but I checked from the browser, and it shows sessionID cookie. But I cannot extract it using this code to authenticate user. Thank you.
You should pay attention on the HTML form fields.
There is often hidden fields required in order to achieve the post process correctly.
Take at look the html source of the login form on this website (inspect element...)
The form fields are: "user", "pass" plus two hidden fields "form_build_id" and "form_id".
Try adding this in your 'getFormParams' function:
paramList.add(new BasicNameValuePair("form_id","user_login_block"));
I need to follow redirects given to me by HTTPost. When I make an HTTPost, and try to read the response, I get the redirect's page html. How can I fix this? Code:
public void parseDoc() {
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, true);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://secure.groupfusion.net/processlogin.php");
String HTML = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("referral_page",
"/modules/gradebook/ui/gradebook.phtml?type=student_view"));
nameValuePairs.add(new BasicNameValuePair("currDomain",
"beardenhs.knoxschools.org"));
nameValuePairs.add(new BasicNameValuePair("username", username
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password
.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String g = httppost.getURI().toString();
HttpResponse response = httpclient.execute(httppost);
HTML = EntityUtils.toString(response.getEntity());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
sting.setText(HTML);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
When a server sends a redirect, it is actually sending a 3xx response code (usually 301 or 302) that indicates the redirect, and a Location header that tells you the new location.
So, in your case, you can get the Location header from the HttpResponse object and use that to send another request to retrieve the actual content after you've logged in. For example:
String newUrl = response.getFirstHeader("Location").getValue();
So long as you reuse the same HttpClient object for both requests, it should use any cookies set by the login request in your subsequent request(s).
Try using the HttpGet method
GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).
For more info refer this
Hope it helps,
Cheers
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Httpclient 4, error 302. How to redirect?
I want to retrieve some information from my comcast account. Using examples on this site, I think I got pretty close. I am using firebug to see what to post, and I see that when I login I am being redirected. I don't understand how to follow the redirects. I have played with countless examples but just can't figure it out. I am new to programming and just not having any luck doing this. Here is my code. I make an initial login, then go to try to go to another URL which is where the redirects begin. Along the way, I see that I am acquiring lots of cookies, but not the important one s_lst.
HttpPost httpPost = new HttpPost("https://login.comcast.net/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("continue", "https://login.comcast.net/account"));
nvps.add(new BasicNameValuePair("deviceAuthn", "false"));
nvps.add(new BasicNameValuePair("forceAuthn", "true"));
nvps.add(new BasicNameValuePair("ipAddrAuthn", "false"));
nvps.add(new BasicNameValuePair("lang", "en"));
nvps.add(new BasicNameValuePair("passwd", "mypassword"));
nvps.add(new BasicNameValuePair("r", "comcast.net"));
nvps.add(new BasicNameValuePair("rm", "2"));
nvps.add(new BasicNameValuePair("s", "ccentral-cima"));
nvps.add(new BasicNameValuePair("user", "me"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
System.out.println("executing request " + httpPost.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpPost, responseHandler);
String cima = StringUtils.substringBetween(responseBody, "cima.ticket\" value=\"", "\">");
System.out.println(cima);
HttpPost httpPost2 = new HttpPost("https://customer.comcast.com/Secure/Home.aspx");
List <NameValuePair> nvps2 = new ArrayList <NameValuePair>();
nvps2.add(new BasicNameValuePair("cima.ticket", cima));
httpPost2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));
System.out.println("executing request " + httpPost2.getURI());
// Create a response handler
ResponseHandler<String> responseHandler2 = new BasicResponseHandler();
String responseBody2 = httpclient.execute(httpPost2, responseHandler2);
System.out.println(responseBody2);
Here's a sample adapted from the 'Response Handling' example here.
Your example is quite complicated - best to simplify your code while you figure out how to follow redirects (you can comment out the section I've highlighted to show the example failing to follow the redirect).
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.protocol.*;
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
// Comment out from here (Using /* and */)...
httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect=false;
try {
isRedirect = super.isRedirected(request, response, context);
} catch (ProtocolException e) {
e.printStackTrace();
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return false;
}
});
// ...to here and the request will fail with "HttpResponseException: Moved Permanently"
try {
HttpPost httpPost = new HttpPost("http://news.bbc.co.uk/");
System.out.println("executing request " + httpPost.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println(responseBody);
// Add your code here...
} finally {
// When HttpClient instance is no longer needed, shut down the connection
// manager to ensure immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}