HttpClient unable to 302 this link? - java

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

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

Encoding issue Android / REST /JSON

i´m trying to solve encoding issue for response (json) from simple rest service in my app for about one day now, no more ideas..
when i open response in restclient, getting correct result:
Status Code: 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 270
Content-Type: application/json; charset=utf-8
Date: Wed, 13 Apr 2016 09:26:39 GMT
Keep-Alive: timeout=15, max=100
Server: Apache
Vary: Accept-Encoding
response:
{"reqStatus": 1,
"articles": [
{
"articleId": "1",
"articleName": "Schüssel 18cm",
"articlePrice": "34.50",
"articleDate": "2016-03-15 17:34:00",
"userZip": "76879",
"userCity": "Ottersheim",
"articleImages": [ ...
for inputstream getting that:
{"reqStatus":1,"articles":[{"articleId":"1","articleName":"Sch\u00fcssel 18cm","articlePrice":"34.50","articleDate":"2016-03-15 17:34:00","userZip":"76879","userCity":"Ottersheim","articleImages":[ ...
code for request:
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("POST");
if (headers!=null&&headers.length>0){
for (int i=0;i < headers.length;i++){
urlConnection.setRequestProperty(headers[i][0].toString(), headers[i][1].toString());
}
}
urlConnection.connect()
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
return new JSONObject(inputStr);
}
any ideas?

How to get response code of httpPut in 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.

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.

Categories

Resources