Java - Keep getting a path error even after using urlencode - java

I'm simply trying to do a HttpGet.
Here is the string that is being passed:
fullString = "?nOne=" + node1 + "&nTwo=" + node2 + "&nThree=" + node3 + "&nFour=" + node4 + "&power=" + power + "&color=" + colorRGB;
All the variables are a single integer except for color which is 9 digits.
That string is passed to a function doing the following:
String get_url = URLEncoder.encode("http://192.168.30.80/" + str, "UTF-8");
HttpClient Client = new DefaultHttpClient();
HttpGet httpget;
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpget = new HttpGet(get_url);
String content = Client.execute(httpget, responseHandler);
I originally just tried:
String get_url = "http://192.168.30.80/" + str;
But that gave me an illegal character error. After trying urlencode now I get a:
java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://192.168.30.80/[Ljava.lang.String;#1a50d830
Why can't it just be a string? (Obviously this is my first attempt with android/java)
Please help me understand what is going wrong, thanks.

URLEncoder.encode does not encode a full URL but should be used for the values of the GET parameters.
eg.
fullString = "?nOne=" + URLEncoder.encode(node1, "UTF-8");
fullString += "&nTwo=" + URLEncoder.encode(node2, "UTF-8");

Looking at the response, the path is not getting parsed to extract the scheme or host as these are both null.
Looking at the documentation, it should work from a string. Have you checked that the string is correctly encoded? It seems like it is unable to identify the scheme or host.
You could try inspecting the string value before it is passed to the HttpGet, or you might want to try using a URI.
URI address = new URI("http://192.168.30.80/" + str);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(address);
HttpResponse response = client.execute(request);

Related

Can't pass request parameters using http post

I have a requirement to call a controller from java code itself. The controller is as follows,
#RequestMapping(value = "temp", method = RequestMethod.POST)
#ResponseBody
public String uploadDataFromExcel(#RequestBody Map<String, String> colMapObj, #ModelAttribute ReqParam reqParam) {
}
I am trying to call the above controller using http post as follows,
String url ="http://localhost:8081/LeadM" + "/temp/?searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
InputStream rstream = entity.getContent();
jsonObject = new JSONObject(new JSONTokener(rstream));
where reqParam is a class object is the class object and colMapObj is the map that I want to pass to the above controller. However when http post is executed it gives exception in the url.
If anybody knows the right way then please suggest, thank you.
This should work
#RequestMapping(value = "/temp", method = RequestMethod.POST)
#ResponseBody
public String uploadDataFromExcel(#RequestBody Map<String, String> colMapObj, #ModelAttribute ReqParam reqParam) {
}
and url should be
String url ="http://localhost:8081/LeadM" + "/temp?"+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
URL dos not work with spaces.From your code above: " &exportDiscardRec="
To avoid such issues use URIBuilder or something similar if possible.
Now for the request, you are not building your request correctly for example you do not provide the body.
Check below example:
Map<String, String> colMapObj = new HashMap<>();
colMapObj.put("testKey", "testdata");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
JSONObject body = new JSONObject(colMapObj);
StringEntity entity = new StringEntity(body.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getEntity().toString());
client.close();
More examples just google "apache http client post examples" (e.g. http://www.baeldung.com/httpclient-post-http-request)
Encode your query string.
String endpoint = "http://localhost:8081/LeadM/tmp?";
String query = "searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
String q = URLEncoder.encode(query, "UTF-8");
String finalUrl = endpoint + q;
If this doesn't work, then encode individual params before concatenating.
On a side note
if you r running in same jvm then you can call method directly
if you own the the upload method then consider changing query string into form param

Parse Chinese characters with URLEncodedUtils in Java

I have a uri like
http://localhost/?name=foo&value=bar
And I use
org.apache.http.client.utils.URLEncodedUtils.parse(URI uri, String encoding)
to get a list of NameValuePairs, and it works nicely. But now I have need also the possibility to parse Chinese charecters, e.g.:
http://localhost/?name=生产者&value=单车
But URLEncodedUtilsparse fails to parse these characters correctly. How can I retrieve them and get a list of NameValuePairs again?
You can try like this:
String query1 = URLEncoder.encode("生产者", "UTF-8");
String query2 = URLEncoder.encode("单车", "UTF-8");
String url = "http://localhost/?name=" + query1 + "&value=" + query2;
Also check the java.net.URLEncoder
I faced the similar situation. URLEncodedUtils must be used with StringEntity. UrlEncodedFormEntity is broken.
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(
URL);
List<NameValuePair> param_data = new ArrayList<>();
param_data.add(new BasicNameValuePair("name", [STRING_FOREIGN CHARS));
String s = URLEncodedUtils.format(param_data, java.nio.charset.Charset.forName("UTF-8"));
StringEntity entity = new StringEntity(s, java.nio.charset.Charset.forName("UTF-8"));
postRequest.setEntity(entity); // don't use postRequest.setEntity(new UrlEncodedFormEntity(param_data));
HttpResponse response = httpClient.execute(postRequest);
..[snipped] do whatever you want with response

Square brackets causing error in URL string in android

Hi im having a problem with executing a URL in Android, I am sure it is related to the square brackets but I cant find any solution. Any suggestions would be welcome.
protected String doInBackground(String... arg0) {
try {
int indexdevice = 12;
String uuu = URLEncoder.encode ("http://<ipaddress>/ZWaveAPI/Run/devices[2].instances[0].commandClasses[0x25].Set(255)", "UTF-8");
HttpClient Client = new DefaultHttpClient();
String SetServerString = "";
HttpGet httpget = new HttpGet(uuu);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget,responseHandler);
Log.v("NAS", "--------- amount is " + SetServerString);
}
catch (Exception ex)
{
Log.v("NAS",String.valueOf(ex));
}
The error I am getting is:
07-08 12:37:33.970: V/NAS(1800): java.lang.IllegalStateException:
Target host must not be null, or set in parameters. scheme=null, host=null,
You are url encoding the complete url, including http and hostname. That won't work. Just encode the part after the host address:
String uuu = "http://<ipaddress>/"+URLEncoder.encode ("ZWaveAPI/Run/devices[2].instances[0].commandClasses[0x25].Set(255)", "UTF-8");
the http:// is probably getting encoded try something like
String foo = foo.replaceFirst("http://", ""); foo = "http://"+ foo

Computed Amazon MWS signature does not match

I am relatively new to Java and have been stuck for a few days trying to get my application to 'POST' a HTTP request to Amazon's MWS API. I keep getting a 'SignatureDoesNotMatch' response and I cannot figure out why. I have used Amazon's MWS scratchpad extensively, and using it I don't have any trouble getting successful responses, so my keys etc are OK. The content parameters and base64 signature generated by the scratchpad match what my application generates, so I am confident that my application is correctly compiling the parameters and signature. When I hardcode the content parameters generated by the scratchpad into my application I get the 'SignatureDoesNotMatch'error response. I would be very grateful for any pointers from more experienced Java developers or anyone who has produced an application like mine working on Amazon's MWS.
The relevant section of my code is:
/*
* get amazon timestamp
*/
GetAmazonTimestamp timestampObj = new GetAmazonTimestamp();
String amazonTimestamp = null;
try {
amazonTimestamp = timestampObj.getTimestamp();
amazonTimestamp.replace(".000Z", "Z");
} catch (IOException e) {
e.printStackTrace();
}
/*
* create http parameters and initialise the signature value
*/
String URLendpoint = "https://mws.amazonservices.co.uk/orders/2011-01-01";
String param1 = "AWSAccessKeyId"; String value1 = "AKIAIZXBKLVSGBBQQL2A";
String param2 = "Action"; String value2 = "ListOrders";
String param3 = "LastUpdatedAfter"; String value3 = "2013-02-01T00:00:00Z";
String param4 = "MarketplaceId.Id.1"; String value4 = "A1F83G8C2ARO7P";
String param5 = "SellerId"; String value5 = "A3A2272JFHXROO";
String param6 = "SignatureMethod"; String value6 = "HmacSHA256";
String param7 = "SignatureVersion"; String value7 = "2";
String param8 = "Timestamp"; String value8 = amazonTimestamp;
String param9 = "Version"; String value9 = "2011-01-01";
String param10 = "Signature"; String value10 = null;
/*
* build sections of URL components for signature
*/
String URLforSignature = "POST\n" + "mws.amazonservices.co.uk\n" + "/Orders/2011-01-01\n" +
URLEncoder.encode(param1,"UTF-8") + "=" +
URLEncoder.encode(value1,"UTF-8") + "&" +
URLEncoder.encode(param2,"UTF-8") + "=" +
URLEncoder.encode(value2,"UTF-8") + "&" +
URLEncoder.encode(param3,"UTF-8") + "=" +
URLEncoder.encode(value3,"UTF-8") + "&" +
URLEncoder.encode(param4,"UTF-8") + "=" +
URLEncoder.encode(value4,"UTF-8") + "&" +
URLEncoder.encode(param5,"UTF-8") + "=" +
URLEncoder.encode(value5,"UTF-8") + "&" +
URLEncoder.encode(param6,"UTF-8") + "=" +
URLEncoder.encode(value6,"UTF-8") + "&" +
URLEncoder.encode(param7,"UTF-8") + "=" +
URLEncoder.encode(value7,"UTF-8") + "&" +
URLEncoder.encode(param8,"UTF-8") + "=" +
URLEncoder.encode(value8,"UTF-8") + "&" +
URLEncoder.encode(param9,"UTF-8") + "=" +
URLEncoder.encode(value9,"UTF-8");
/*
* hash and base64 encode the signature using the URLforSignature
*/
GetAmazonSignature signatureObj = new GetAmazonSignature();
value10 = signatureObj.getSignature(URLforSignature);
/*
* create the http post
*/
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URLendpoint);
String line = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
nameValuePairs.add(new BasicNameValuePair(param1, value1));
nameValuePairs.add(new BasicNameValuePair(param2, value2));
nameValuePairs.add(new BasicNameValuePair(param3, value3));
nameValuePairs.add(new BasicNameValuePair(param4, value4));
nameValuePairs.add(new BasicNameValuePair(param5, value5));
nameValuePairs.add(new BasicNameValuePair(param6, value6));
nameValuePairs.add(new BasicNameValuePair(param7, value7));
nameValuePairs.add(new BasicNameValuePair(param8, value8));
nameValuePairs.add(new BasicNameValuePair(param9, value9));
nameValuePairs.add(new BasicNameValuePair(param10, value10));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
Thanks for your help.
Thanks to those who helped me with this, but I finally worked out that "https://mws.amazonservices.co.uk/orders/2011-01-01" needs a capital "O" in orders. Amazon's development support agree that the 'SignatureDoesNotMatch' error message is not very helpful in this case and have said that they will look into it.
Thanks again
Why not use the Java Client libraries Amazon provides for MWS?
Go to MWS and click on the API you are interested in. You will see a Java Client library link where you can go and get the files you need. They contain examples and will handle the URL signing, parsing, and other work you would normally have to do yourself.
The way you construct URLforSignature seems okay.
You aren't showing your code for GetAmazonSignature, though. I would suspect the flaw to be in there. May be you forgot to base64-encode your result? Note that the MWS scratchpad shows both the hex signature as well as the base64 encoded one on the "Request Details" page. You should be able to find the flaw by comparing those details with your function results.

URL Illegal Character

Here is my code:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.d("URL", convertURL(URL));
request.setURI(new URI(URL));
HttpResponse response = client.execute(request);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
I don't know which error in my URL:
http://localhost/CyborgService/chatservice.php?action=recive_game&nick_sender=mkdarkness&pass=MV030595&date_last=2012-11-18 09:46:37&id_game=1
I have already used a function to convert URL, but has not worked. But, if I trying open this URL in my Browser, it opens successfully.
Here is my error:
11-18 21:46:37.766: E/GetHttp(823): java.net.URISyntaxException: Illegal character in query at index 127: http://192.168.0.182/CyborgService/chatservice.php?action=recive_game&nick_sender=mkdarkness&pass=MV030595&date_last=2012-11-18 09:46:37&id_game=1
There is a space in your URL, in position 127. The date is generated as "date_last=2012-11-18 09:46:37", which causes an error when opening the URL.
Spaces are not formally accepted in URLs, although your browser will happily convert it to "%20" or to "+", both valid representations of a space in a URL. You should escape all characters: you can replace space with "+" or just pass the String through URLEncoder and be done with it.
To use URLEncoder see e.g. this question: encode with URLEncoder only parameter values, not the full URL. Or use one of the constructors for URI which have a few parameters, not a single one. You are not showing the code that constructs the URL so I cannot comment on it explicitly. But if you have a map of parameters parameterMap it would be something like:
String url = baseUrl + "?";
for (String key : parameterMap.keys())
{
String value = parameterMap.get(key);
String encoded = URLEncoder.encode(value, "UTF-8");
url += key + "&" + encoded;
}
Some other day we can talk about why Java requires to set the encoding and then requires that the encoding be "UTF-8", instead of just using "UTF-8" as the default encoding, but for now this code should do the trick.
There is a whitespace character:
...2012-11-18 09:46:37... (at index 127, just like the error message says).
Try replacing it with %20
Do this way it will definetly help you
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/SendMessage");
try {
//Your parameter should be as..
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("messageText", msgText));
nameValuePairs.add(new BasicNameValuePair("senderUserInfoId", loginUserInfoId));
//set parameters to ur URL
myConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute the connection
HttpResponse response = myClient.execute(myConnection);
}
catch (ClientProtocolException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}

Categories

Resources