I have to use HEAD method of HttpClient to get the header field and to check the "last-modified" date of server file.
I am not able to get that, if you know how to get the header field then please reply.
How to get the "last-modified" header into the String object for the comparison.
Here is my code:
HttpClient client = new DefaultHttpClient();
//HttpGet get = new HttpGet(url);
HttpHead method = new HttpHead(url);
HttpResponse response= client.execute(method);
Header[] s = response.getAllHeaders();
System.out.println("THe header from the httpclient:");
for(int i=0; i < s.length; i++){
Header hd = s[i];
System.out.println("Header Name: "+hd.getName()
+" "+" Header Value: "+ hd.getValue());
}
On httpClient 4.5 you would use:
final HttpHead headMethod = new HttpHead(fileUri);
final Header header = headMethod.getFirstHeader("last-modified");
final String lastModified = header.getValue();
From the HttpClient documentation
HeadMethod head = new HeadMethod("http://jakarta.apache.org");
// Excecute the method here with your HttpClient
Header[] headers = head.getResponseHeaders();
String lastModified = head.getResponseHeader("last-modified").getValue();
You'll need to add your own error handling.
It would be best to use something like this:
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpHead head = new HttpHead(url);
String lastModified;
try {
CloseableHttpResponse response = client.execute(head);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
Header header = headMethod.getFirstHeader("last-modified");
lastModified = header.getValue();
}
} catch (IOException ignored) {
}
Related
I have the following Java code to send a POST request to SharePoint REST API to create a list and it returns the following authentication errors:
CloseableHttpClient httpClient = null;
try {
String user = xxx;
String password = xxx;
String domain = xxx;
String workstation = "";
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
new NTCredentials(user, password, workstation, domain));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
String digestQueryURL = "http://my_sharepoint_site/_api/contextinfo";
HttpPost httpPost = new HttpPost(digestQueryURL);
httpPost.addHeader("Accept", "application/json;odata=verbose");
CloseableHttpResponse response = httpClient.execute(httpPost);
byte[] content = EntityUtils.toByteArray(response.getEntity());
String jsonString = new String(content, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree(jsonString);
String formDigestValue = j.get("d").get("GetContextWebInformation").get("FormDigestValue").toString();
response.close();
// now try to create the list
String url = "http://my_sharepoint_site/_api/web/lists";
HttpPost httpPost2 = new HttpPost(url);
httpPost2.addHeader("X-RequestDigest", getFormDigest(httpClient));
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
String body = "{ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }";
StringEntity se = new StringEntity(body);
httpPost2.setEntity(se);
CloseableHttpResponse response2 = httpClient.execute(httpPost2);
StringBuilder result = new StringBuilder();
System.out.println(response2.getStatusLine().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(response2.getEntity().getContent()));
String output;
while ((output = br.readLine()) != null) {
result.append(output);
}
System.out.println(result.toString());
} catch (Exception e) {
}
Console output
HTTP/1.1 403 FORBIDDEN
{"error":{"code":"-2130575251, System.Runtime.InteropServices.COMException","message":{"lang":"en-US","value":"The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."}}}
I can use very similar code to send GET requests to the REST API to retrieve all lists, retrieve list items, perform all these read operations. However this does not work for POST requests. Am I doing something wrong? The credentials provided are for an account that has full control over the entire site collection, so we can rule out permission errors.
Alright, the problem is really very simple. This line:
String formDigestValue = j.get("d").get("GetContextWebInformation").get("FormDigestValue").toString();
Returns the formDigestValue with quotation marks enclosing it. Using asText() instead of toString() helped.
I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity for your PostMethod:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity for binary data are ByteArrayRequestEntity for byte[], FileRequestEntity which reads the data from a file (since 3.1) and InputStreamRequestEntity, which can read from any input stream.
Before 3.0 you can directly set a String or an InputStream, e.g. a ByteArrayInputStream, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity implementations: ByteArrayEntity, InputStreamEntity, FileEntity, ...
i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name
my code
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
Answer
I try to send cookies with a form post using the Apache HttpClient and, for some reason, the server gets the request but not the cookies. Here is my code:
DefaultHttpClient client = new DefaultHttpClient();
// Set the cookies...
{
String Domain = MyGetParameter("Domain");
BasicCookieStore cookieStore = new BasicCookieStore();
String[] strs = GetParameterSplitted("PostCookies");
int size = strs.length;
for (int i=0; i<size-1; i+=2)
{
//JOptionPane.showMessageDialog(null, strs[i]+" = "+FromBase64(strs[i+1], "UTF-8"));
BasicClientCookie cookie = new BasicClientCookie(strs[i], FromBase64(strs[i+1], "UTF-8"));
cookie.setDomain(Domain);
cookie.setPath("/");
//cookie.setSecure(true);
cookieStore.addCookie(cookie);
}
client.setCookieStore(cookieStore);
}
HttpPost post = new HttpPost(url.toURI());
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(10);
// Set the form POST parameters...
{
String[] strs = GetParameterSplitted("PostParams");
int size = strs.length;
for(int i=0; i<size-1; i+=2)
{
String name = strs[i].trim();
String value = FromBase64(strs[i+1].trim(), "UTF-8");//, "UTF-8"
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
post.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
post.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse response = client.execute(post);
int StatusCode = response.getStatusLine().getStatusCode();
The site uses HTTP (not HTTPS), I make sure the domain name is set correctly to the cookies (http://mysite) and the cookies seem to be set correctly when the above code executes.
Does anyone have any idea why it's failing to pass them to the server?
I have seen other similar questions on this site but nothing seemed to help.
You look closely, if the date of your cookie expired httptClient not send this cookie, on this that you should put the cookies date.
And in domain name will be no "http://", only simply domain name.
For Example:(http://www.gmail.com => like this to write setDomain("www.gmail.com"))
This example i add 100 day to current day and set cookie.
Example send post data via HttpClient with cookie:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
Date date = calendar.getTime();
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.setCookieStore(new BasicCookieStore());
BasicClientCookie cookie = new BasicClientCookie(YourCookieName, YourCookieValue);
cookie.setDomain(YourDomain);
cookie.setExpiryDate(date);
cookie.setPath("/");
httpClient.getCookieStore().addCookie(cookie);
....
httpClient.execute(yourHttpUriRequest);
Below is a snipped from a Java Client that connects to a website and uploads a file via the POST method. I have to reproduce this client in a Visual Studio environment, but I don't see any equivalent functions in the .NET environment for the setEntity() function used in the Java.
Everything I've found points to using this...
public void uploadFile(File uploadFile, String partner, String key,
String baseUrl,boolean isPartner) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1
);
String url = baseUrl + "?" + (isPartner ? "partnerId" : "ori") + "="
+ partner.toUpperCase() + "&authKey="
+ key+ "&key="
+ key;
HttpPost httppost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(uploadFile, "text/xml");
multipartEntity.addPart("dataFile", contentBody);
httppost.setEntity(multipartEntity);
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Everything I've found in Visual studio uses something like this below for the POST method. The WebRequest object has no obvious way of adding the parameters I need.
Dim request As WebRequest = WebRequest.Create("http://Test.com/import?partnerId=2&authKey=XdUa")
request.Method = "POST"
Dim postData As String = StrData
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "dataStr"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Any guidance would be greatly appreciated. If my question is not clear, let me know, I'll try again.
You can add following code snippet to add the parameter
request.ContentType="application/x-www-form-urlencoded"
Dim postData As String = "name1="+value1+"&name2="+value2
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Rest will remain same.
I need to encode the params to ISOLatin which i intend to post to the site. I'm using org.apache.http. libraries. My code looks like follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("www.foobar.bar");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpParams params = new BasicHttpParams();
params.setParameter("action", "find");
params.setParameter("what", "somebody");
post.setParams(params);
HttpResponse response2 = httpClient.execute(post);
Thank you!
You are setting parameters wrong. Here is an example,
PostMethod method = new PostMethod(url);
method.addParameters("action", "find");
method.addParameters("what", "somebody");
int status = httpClient.executeMethod(method);
byte[] bytes = method.getResponseBody();
response = new String(bytes, "iso-8859-1");
if (status != HttpStatus.SC_OK)
throw new IOException("Status code: " + status + " Message: "
+ response);
The default encoding will be Latin-1.