I have the following code to send a WFS request to a locally running GeoServer instance using the Apache http-client-4.1 library:
ThreadSafeClientConnManager connectionMngr = new ThreadSafeClientConnManager();
DefaultHttpClient httpClient = new DefaultHttpClient(this.connectionMngr);
HttpPost httpPost = new HttpPost(wfsUrl);
httpPost.setEntity(new StringEntity(wsft, HTTP.UTF_8));
log.debug("Submitting WSFT request: " + wsft);
BasicResponseHandler responseHandler = new BasicResponseHandler();
String result = httpClient.execute(httpPost, responseHandler);
log.debug("Result of WSFT request: " + result);
The data I am retrieving from the GIS database is encoded in UTF-8, and all the features I would expect to find are found. However, any special characters are not being printed properly by my debug statements, or being displayed properly in the front end of my application (a Spring MVC web app).
I know the values are being stored correctly in my GIS database as I can see them via SQL client and they are printed as I would expect. I can also see the names of Roads etc which use special characters are being printed properly on my map layers which suggests the GeoServer is configured correctly.
Instead of passing in a BasicResponseHandler, use the HttpClient.execute(HttpUriRequest) method which returns a HttpResponse and then use EntityUtils.toString(HttpEntity, "UTF-8"), pseudo:
HttpResponse r = httpClient.execute(httPost)
String utf8encodedEntity = EntityUtils.toString(r.getEntity(), "UTF-8");
Related
I am trying to POST a request using JAVA HTTPCLIENT, and while doing so, I am getting 404 Bad Request.
I tried writing the JAVA code in Eclipse and got 404 Bad Request and tried sending the request through POSTMAN and received HTTP Status 500
package com.apex.customer.service;
public class CustServicePostTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/102";
//create the http client
HttpClient client = HttpClientBuilder.create().build();
//create the post message
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("ID", "102"));
urlParameters.add(new BasicNameValuePair("FIRSTNAME", "Apex"));
urlParameters.add(new BasicNameValuePair("LASTNAME", "Consultancy"));
urlParameters.add(new BasicNameValuePair("STREET", "Shell Blvd"));
urlParameters.add(new BasicNameValuePair("CITY", "Fremont"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
System.out.println("Parameters : " + urlParameters);
System.out.println("Response Code: " + response);
System.out.println(response.getStatusLine().getReasonPhrase());
}
}
I am looking for 200 OK request.
The issue here is due few mistakes:
First is related to the input format. The code you're using tries to map key and values, but as I could see from this guide, it expects a XML format in a plain text as input.
The second mistake is that you are trying to post over an existing ID. In this case, to create a resource you should use http://www.thomas-bayer.com/sqlrest/CUSTOMER/
So in this case in order to make it work, try something like this:
String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String xml = "<resource>";
xml += "<ID>102</ID>";
xml += "<FIRSTNAME>Apex</FIRSTNAME>";
xml += "<LASTNAME>Consultancy</LASTNAME>";
xml += "<STREET>Shell Blvd</STREET>";
xml += "<CITY>Fremont</CITY>";
xml += "</resource>";
post.setEntity(new StringEntity(xml));
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
System.out.println("Response Code: " + response);
System.out.println(response.getStatusLine().getReasonPhrase());
It is also very useful to learn another way to test it with tools like curl command line utility. For example you can POST a product like this:
curl -X POST http://www.thomas-bayer.com/sqlrest/PRODUCT/ -d '<resource><ID>103</ID><NAME>X</NAME><PRICE>2.2</PRICE></resource>'
Once you solve this, it will be important to get used with HTTP codes. For example a 500 error means something wrong on the server side while a 404 usually means that you're hitting an invalid endpoint (it does not exists).
Finally, I'll not discuss why are you using this project to send HTTP requests to a server - but keep in mind that this is not a very common way to go. Currently the REST with JSON would be much more interesting and enjoyable :) In case you're interested on it, take a look on Spring Boot REST
I am using Java, Spring boot and Apache HttpClient to try send a post request. The documentation of the resource I am trying to reach can be found here:
https://docs.enotasgw.com.br/v2/reference#incluiralterar-empresa
Below is my code:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(incluirEmpresa);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
post.setHeader("Authorization", "Basic " + apiKey);
try {
StringEntity entity = new StringEntity(json);
//tried to add these two lines to see if they would fix the error, but it is the same
entity.setContentEncoding("application/json");
entity.setContentType("application/json");
post.setEntity(entity);
System.out.println(json);
System.out.println("======================");
CloseableHttpResponse response = httpClient.execute(post);
System.out.println(response.getStatusLine().getReasonPhrase() + " - " + response.getStatusLine().getReasonPhrase());
idEmpresa = response.getEntity().getContent().toString();
}
My response is 400 - Bad Request. On the interactive documentation link above, when I post my Json, I receive the error of duplicate entry, which is what I expect since the information I am sending is already on the database.
Since the interactive documentation returns the error of duplicate, I know the problem is not within my json format, but on my post request. The documentation have samples on C#, but not on Java, which is what I am using.
By the way, the json is variable is a string in case this is relevant.
Could someone try to point to me what is wrong with my post code?
Found out what I was missing.
After reviewing what was being sent to the API, i noticed the json was not in the expected format. So I did some research and found that, at least for my case, setting the headers with the content type was not enough, I also had to set the Entity that was being set to the HttpPost, to do that, i had to change this line of the code:
StringEntity entity = new StringEntity(json);
to this:
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
After that change, the requests started to work as expected.
I am transitioning an existing service from using google url shortener api to try and use Firebase Dynamic Links. I have linked a project from the Google Cloud Platform, and setup a "dummy" android app so that I can have the app domain for the dynamic links. I am trying to use the REST API to shorten urls for very long urls that can't be handled by a third party. I have tried sending using:
ObjectMapper mapper = new ObjectMapper();
HttpPost httpPost = new HttpPost("https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=****");
FirebaseDynamicLinkInfo dynamicLinkRequest = new FirebaseDynamicLinkInfo();
dynamicLinkRequest.setDynamicLinkDomain("zw5yb.app.goo.gl");
dynamicLinkRequest.setLink(assetUrl);
httpPost.setEntity(new StringEntity(mapper.writeValueAsString(dynamicLinkRequest)));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
responseBody = httpClient.execute(httpPost, responseHandler);
I am getting a 400 Bad Request when I post the request to the API (on the httpCLient.execute line. I have double checked my api-key. I have also tried using just the longDynamicLink parameter, and it gets the 400 Bad Request Response.
Any ideas of where I could be going wrong?
Thanks,
Ben
I contacted Google Support on this one, and I wasn't UrlEncoding my querystring parameters on the deep link. After encoding the link, the request was successful. I went back to using passing json that just had a longDynamicLink property (as opposed to the dynamicLinkInfo object in my original post). Here is what it looks like:
String myEscapedUrl = "https://zw5yb.app.goo.gl/?link=" + URLEncoder.encode(assetUrl, "UTF-8");
FirebaseDynamicLinkRequest dynamicLinkRequest = new FirebaseDynamicLinkRequest(myEscapedUrl);
httpPost.setEntity(new StringEntity(mapper.writeValueAsString(dynamicLinkRequest)));
// inform the server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
responseBody = httpClient.execute(httpPost, responseHandler);
POST request to server using java URLConnnection
I need to send a POST request with the two parameters below:
param1=value1
param2=value2
And also I need to send a file.
In the case of Apache these 2 two(sending params and file) things are handled like below
post.setQueryString(queryString) // queryString is url encoded for eg: param1=value1¶m2=value2
post.setRequestEntity(entity) // entity is constructed using file input stream with corresponding format
Please let me know if you have anything related to this problem.
Please note: When I try using Google Chrome REST client plug-in, I am getting the response as below (tried with all request content-types)
UNSUPPORTED FILE FORMAT: 'multipart/form-data' is not a supported content-type
Response code is 400.
Try this API from Apache to send request internally with POST method.
The below is the sample Code to use API
List<org.apache.http.NameValuePair> list =new ArrayList<org.apache.http.NameValuePair>();
HttpPost postMethod = new HttpPost("http://yoururl/ProjectName");
list.add(new BasicNameValuePair("param1", "param1 Value")) ;
postMethod.setEntity(new UrlEncodedFormEntity(list));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(postMethod);
InputStream is = response.getEntity().getContent();
I have .net web service that expect JSON object. This web service has method for return token:
public string GetToken(string username, string password)...
This is my site url for direct access (when I field manually id, method and params and paste in browser url I receive response )
http://mysite.com/JsonRPC.aspx?id={0}&method={1}¶ms={2}
On stackoverflow I found way to create and send JSON object in android , here is example:
HttpPost request = new HttpPost(URL);
JSONStringer json = new JSONStringer()
.object()
.key("username").value("username")
.key("password").value("password")
.endObject();
Log.i("json",json.toString());
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
My problem is that I don't know how to call my .net web service. What format should be URL variable , where to specific method name , and how to specific method parameters ?
Please give me code
Thanks
I would use this library.
http://code.google.com/p/android-json-rpc/
There are examples on the website that should be sufficient for you.