Hi am sending a url using apache HttpClient by using following code but it has been showing a exception :java.net.URISyntaxException:
Illegal character in query at index 70: http://192.155.2.144:8080/SDAX/homePage.do?actionFlag=istrict&&MSG=1|Bdrtfggf|254td|return|null|null|null
Please help me where iam doing the problem. the following code i am sending a URL
String MSG="1|Bdrtfggf|254td|return|null|null|null" ;
String url="http://192.168.2.144:8080/SDAX/homePage.do?actionFlag=edistrict&&MSG="+MSG;
System.out.println("Url is"+url);
//String url = "http://192.168.0.6:8084/NRC_NEW_SEARCH/getVillageList.req?dist_id=1";
//String url="http://192.168.0.85:8080/poly/web/";
//FacesContext.getCurrentInstance().getExternalContext().redirect(url);
//ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
//context..redirect(url);
HttpRequestBase request = new HttpGet(url);
/*HttpParams params = new BasicHttpParams();
params.setParameter("dist_id", "1");
request.setParams(params);*/
HttpClient httpClient = new DefaultHttpClient();
httpClient.execute(request);
You should encode the MSG string before creating a URL from it.
String encodedMSG = URLEncoder.encode(MSG, "UTF-8")
String url="http://192.168.2.144:8080/SDAX/homePage.do?actionFlag=edistrict&&MSG="+ encodedMSG;
Edit
There won't be any problem in retrieving the data after encoding. If you have programmed this servlet homePage.do then you should use URLDecoder.decode() method in it.
Since vertical bar(|) is not a valid URI character thats why You are getting URISyntaxException.
Solution:
As suggested by kaysush, you need to encode/decode your url.
For more on this, Please check folowing url:
Cannot process url with vertical/pipe bar
You havn't explained what you are trying to achieve here. I hope it isn't by mistake. but
As per you question, You are trying to post a url and In your code you are using HttpGet(url);
Related
I have a block of codes to read URL page content, This code is working good for many pages but does not work for some pages like the link below:
https://www.deutschepost.com/en/business-customers.html/robots.txt
my code is something like this:
String url = https://www.deutschepost.com/en/business-customers.html/robots.txt
HttpGet request = new HttpGet(url);
//requesting the data using execute();
CloseableHttpResponse response = httpClient.execute(request);
//below is for openStream();
InputStream robotTxtStream = new URL(url).openStream();
I am not getting any response not even exception from both "openStream();" or"execute()".
Thanks in advance!!
I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
I have a login that needs an email and password.
If I hit it from Postman rest client with this:
www.site.com/login.json?session[email]=bob#gmail.com&session[password]=password
The server (Rails) will read it just fine, like this:
{"session"=>{"email"=>"bob#gmail.com", "password"=>"password"}, "action"=>"create", "controller"=>"sessions", "format"=>"json"}
But, if I send in the same thing with HTTPGet from android, like this:
HttpClient httpclient = new DefaultHttpClient();
//get the parameters
String email = params[0];
String password = params[1];
String url = "http://www.site.com/login.json?session[email]=" + email + "?session[password]=" + password;
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json");
response = httpclient.execute(httpget);
The server doesn't recognize the parameters, and I end up with an empty json object like this:
{"session"=>{}, "action"=>"create", "controller"=>"sessions", "format"=>"json"}
Anybody know how to form the parameters in this HTTPGet call in android to work like it will in a the rest client call? Thanks!
It seems you have a typo in URL and params get messed up. This line:
String url = "http://www.site.com/login.json?session[email]=" + email + "?session[password]=" + password;
should be
String url = "http://www.site.com/login.json?session[email]=" + email + "&session[password]=" + password;
Note that I've replaced ?session[password]= with &session[password]=.
Do you need to send USER-AGENT or other HTTP headers for it to be valid? Did you trace the HTTP connection with Fiddler2 or another HTTP trace? That ? instead of a & is probably it though.
For a type-safe REST client for Android try: http://square.github.io/retrofit/ It works very nice and you don't have to worry about manual parsing.
One thought I have is that you could try encoding the query string of your URL.
String query = URLEncoder.encode("session[email]=" + email + "?session[password]=" + password", "UTF-8");
String url = "http://www.site.com/login.json?" + query;
HttpGet httpget = new HttpGet(url);
....
* Replace the ?session in the URL with &session as its a mistake..
If the issue still persists, then try using a POST request as:
- in the first place exposing the email and password that way isn't safe practice
- and POST variables can be easily be handled in Rails controllers using the params tag eg. params[:tag] where tag is the key in the Json object.
I'm sending an http get/head request using Apache HttpClient 4.x. I'm sending a request with a url like "http://example.com/getAccessToken". I'm expecting the response to be a redirect url with parameters in the returned url like "http://redirecturl.com/?code=accessTokenStuff". I want to be able to parse the response redirect url parameters, i.e. I want to get "accessTokenStuff". How can I do that?
HttpClient client = new DefaultHttpClient();
HttpHead request = new HttpHead(authUrl);
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());//returns 200
request.releaseConnection();
In a nutshell: what I want is executing an original url and then getting the result which is another url that has a parameter called "code". Then I want to get the value of that parameter.
EDIT:
I also tried this but it returns the same original URL
DefaultHttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpClientParams.setRedirecting(params, false);
HttpGet request = new HttpGet(authUrl);
HttpResponse response = client.execute(request);
String location = response.getLastHeader("Location").getValue();//returns same original url
System.out.println(location);
request.releaseConnection();
Setting HttpClientParams.setRedirecting(params, true); return null
Http response do not take a form of a "redirect url". Redirect and response are both different (but related) concepts. Redirect usually means "get your response from this address instead of original one".
Having said this, you can prevent HttpClient from following a redirect, see this answer: How to prevent apache http client from following a redirect
When your HttpClient is not following the redirect, you can inspect the 'Location:' header of its response, eg:
HeaderIterator iterator = httpResponse.headerIterator("Location");
while(iterator.hasNext()) {
Header header = iterator.nextHeader();
String redirectUrl = header.getValue();
}
I'm executing the following code:
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("(...)&avatarUrl={(...)}&socialId=1&sexo=m&username="));
My problem is I'm getting an illegalArgumentException at letter l from the word avatarUrl, and I don't understand why.
I'll really appreciate your help.
Besides the question of ? oder & in your code, there are cleaner ways to pass parameters:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
BasicHttpParams params = new BasicHttpParams();
params.setParameter("avatarUrl","...")
.setParameter("socialId","...")
.setParameter("sexo","...")
.setParameter("username","...");
request.setParams(params);
HttpResponse response = httpclient.execute(request);
(not tested, but should work)
Note: I heavily edited my original answer due to a little misunderstanding.
Looking at the source code of HttpGet, this exception means that the URL is invalid:
The first query string parameter should be preceded with ?
{ and } are not valid characters for URLs and should be escaped