How to get response code of httpPut in java - java

I am using httpPut to java and I want to get the response code after I execute the command. What it gives me which is "response body" is:
HTTP/1.1 200 OK [Cache-Control: no-cache, no-store, must-revalidate, Pragma: no-cache, Expires: Thu, 01 Jan 1970 00:00:00 GMT, Content-Type: application/json, Transfer-Encoding: chunked, Server: Jetty(8.1.8.v20121106)]
But I only want 200! not the whole thing. Any help?
This is my code by the way:
String url = "http://localhost:80/api/clients/";
String clientID = "1234";
httpclient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(url + clientID);
putRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
putRequest.setHeader("Charset", "UTF-8");
System.out.println(putRequest);
// Add your data
putRequest.setEntity(new StringEntity(clientID, "UTF-8"));
HttpResponse responseBody = httpclient.execute(putRequest);

HTTPResonse having a method called getStatusLine() which return StatusLine Object.
And StatusLine have a method getStatusCode()
So, all you need to write is
HttpResponse responseBody = httpclient.execute(putRequest);
int resultCode = responseBody.getStatusLine().getStatusCode();//200 in your case

responseBody.getStatusLine().getStatusCode() should give you the responsecode of your request.

Related

Java NTLM Athentication for sharepoint online services getting 401 error

i tried the below code for getting lists from a clients sharepoint service (2013) its an https (invalid certificcate),i have downlaoded the same certiite and instaleld in cacets.everytime im getting the below response
try{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new
NTCredentials("username", "passwrd", "host", "domain"));
HttpPut request = new HttpPut("https://domain/_api/get..");
request.setHeader("Content-Type", "application/json;odata=verbose");
request.setHeader("Accept", "application/json;odata=verbose");
System.out.println(httpClient.execute(request));
}catch(Exception e){
throw e;
}
RESPONSE
HTTP/1.1 401 Unauthorized [Server: Microsoft-IIS/8.5,
SPRequestGuid: 6ecb4d9f-9884-c0ba-7e4e-eed562a7e616,
request-id: 6ecb4d9f-9884-c0ba-7e4e-eed562a7e616,
X-FRAME-OPTIONS: SAMEORIGIN,
SPRequestDuration: 4,
SPIisLatency: 0,
WWW-Authenticate: NTLM,
X-Powered-By: ASP.NET,
MicrosoftSharePointTeamServices: 15.0.0.5172,
X-Content-Type-Options: nosniff,
X-MS-InvokeApp: 1;
RequireReadOnly,
Date: Thu,
30 Apr 2020 10:02:57 GMT,
Content-Length: 0] org.apache.http.conn.BasicManagedEntity#679b62af
I got the solution
it because of the port and hostname

How to get token in java

I have the following implementation to get token from form authentication.
The expected output is as follows:
However, when I run my implementation, I am getting as follows. In the response object, I do not see token. I am not an expert on Java, I wonder what I am missing.
Login form get: HTTP/1.1 200 OK
response: HttpResponseProxy{HTTP/1.1 200 OK [Cache-Control: max-age=0, Content-Type: application/json, Date: Fri, 04 Aug 2017 21:05:04 GMT, transaction_id: 729097fd-69ac-b813-26c7-015daf10ddfd, X-Powered-By: Express, Content-Length: 684, Connection: keep-alive] ResponseEntityProxy{[Content-Type: application/json,Content-Length: 684,Chunked: false]}}
Post logon cookies:
None
Here is the source code:
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
HttpHost proxy = new HttpHost("xxx.xxx.xxx.com", 80, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("https://api.xxx.com:443/tokens"))
.addParameter("username", "stackoverflow")
.addParameter("password", "isbest!")
.setConfig(config)
.build();
CloseableHttpResponse response2 = httpclient.execute(login);
HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response2.getStatusLine());
EntityUtils.consume(entity);
System.out.println("response: " + response2);
System.out.println("Post logon cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
When you call EntityUtils#consume(HttpEntity), you are fully consuming the content of the response and closing the underlying stream. However, you haven't actually read the response data into any variable accessible by your code, so you no longer have any opportunity to look at it.
Instead, call one of the methods that fetches the response data. Options for this include HttpEntity#getContent() to access the response body as a raw InputStream or EntityUtils#toString(HttpEntity, Charset) to read the whole response body as a String. (In the latter case, be aware that reading the whole response body at once as a String will impact your process's memory footprint if the response body is large.) After calling either one of those, you can pass the retrieved content through your JSON parser of choice to retrieve the "token".
Once you're all done, it's still good practice to call EntityUtils#consume(HttpEntity) to guarantee cleanup of any underlying resources encapsulated by the entity, such as streams.

POSTing foreign characters using JSON produces 400

I'm trying to make a POST request using JSON with foreign characters, such as the Spanish n with the '~' over it, but I keep getting this request and response error:
POST ...
Accept: application/json
Content-Type: application/json; charset=UTF-8
Content-Length: 151
Content-Encoding: UTF-8
Host: ...
Connection: Keep-Alive
User-Agent: ..
{"numbers":"2","date":"2014-07-15T00:00:00+0000","description":" // this never gets closed
X-Powered-By: ...
Set-Cookie: ...
Cache-Control: ...
Date: Tue, 15 Jul 2014 15:19:12 GMT
Content-Type: application/json
Allow: GET, POST
{"status":"error",
"status_code":400,
"status_text":"Bad Request",
"current_content":"",
"message":"Could not decode JSON, malformed UTF-8 characters (incorrectly encoded?)"}
I can already make a successful POST request with normal ASCII characters, but now that I'm supporting foreign languages, I need to convert the foreign characters to UTF-8 (or whatever the correct encoding ends up being), unless there's a better way to do this.
Here's my code:
JSONObject jsonObject = new JSONObject();
HttpResponse resp = null;
String urlrest = // some url;
HttpPost p = new HttpPost(urlrest);
HttpClient hc = new DefaultHttpClient();
hc = sslClient(hc);
try
{
p.setHeader("Accept", "application/json");
p.setHeader("Content-Type", "application/json");
// setting TimeZone stuff
jsonObject.put("date", date);
jsonObject.put("description", description);
jsonObject.put("numbers", numbers);
String seStr = jsonObject.toString();
StringEntity se = new StringEntity(seStr);
// Answer: The above line becomes new StringEntity(seStr, "UTF-8");
Header encoding = se.getContentType();
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
p.setEntity(se);
resp = hc.execute(p);
When I put a breakpoint and look at se before it's submitted, the characters look right.
UPDATE: code updated with answer a few lines above with a comment identifying it.
The new StringEntity constructor takes a "UTF-8" parameter.

Java - problems with REST client while sending an HTTP request

I am trying to send a GET request to a REST server using Java.
This is the code with some debugging.
URL url = new URL(request);
System.out.println("request url: " + url.toString());
System.out.println("method: " + httpMethod);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(httpMethod);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
OutputStream os = connection.getOutputStream();
os.flush();
String response = os.toString();
System.out.println("response: " + response);
if (response.length() == 0)
{
throw new MyException("the response is empty");
}
This is the output:
request url: http://www.example.com/api.php/getToken/?api_ver=1&token=&api_key=bf8de053d9b6c540fb12195b4ac1602b0a71788c&sig=e00a59747afc7232207d40087e3765a5
method: GET
response:
com.example.api.client.MyException: the response is empty
As you can see, the response is empty.
But if I try and copy and paste the URL in Firefox I get this output
{"error":220}
and this header:
HTTP/1.1 200 OK
Date: Mon, 15 Nov 2010 11:55:29 GMT
Server: Apache
Cache-Control: max-age=0
Expires: Mon, 15 Nov 2010 11:55:29 GMT
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 33
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
Can you see what it is wrong? How could I debug this code further?
Any help would be very much appreciated.
I think you do not use HttpURLConnection properly (there is no connect()).
Maybe study this example.

HttpClient unable to 302 this link?

I found a URL that httpclient doesn't seem to be handling redirects on:
http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGrJk-F7Dmshmtze2yhifxRsv8sRg&url=http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
should 302 to:
http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
when I look at the headers in the browser everything looks good:
HTTP/1.1 302 Moved Temporarily
Content-Type: text/html; charset=UTF-8
Location: http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
Content-Length: 258
Date: Wed, 08 Sep 2010 18:40:21 GMT
Expires: Wed, 08 Sep 2010 18:40:21 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
Server: GSE
Set-Cookie: PREF=ID=024209255b405b06:TM=1283971221:LM=1283971221:S=AG-13_7Cjg_EqlRY; expires=Fri, 07-Sep-2012 18:40:21 GMT; path=/; domain=.google.com
Connection: close
However httpclient doesn't seem to give me the final URL. Here is the code I was using
HttpHead httpget = null;
HttpHost target = null;
HttpUriRequest req = null;
String startURL = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGrJk-F7Dmshmtze2yhifxRsv8sRg&url=http://www.mtv.com/news/articles/1647243/20100907/story.jhtml";
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetcher.emptyCookieStore);
httpget = new HttpHead(startURL);
HttpResponse response = httpClient.execute(httpget, localContext);
Header[] test = response.getAllHeaders();
for(Header h: test) {
logger.info(h.getName()+ ": "+h.getValue());
}
target = (HttpHost) localContext.getAttribute( ExecutionContext.HTTP_TARGET_HOST );
req = (HttpUriRequest) localContext.getAttribute( ExecutionContext.HTTP_REQUEST );
// STILL PRINTS OUT THE GOOGLE NEWS LINK
finalURL = target+""+req.getURI();
Am I doing something wrong? thanks
Found the answer from the httpclient mailing list...
Google doesn't treat a HEAD and GET the same, so the GET redirects with 302 and the HEAD request gives a 200 OK

Categories

Resources