Java - Bing Spatial Data Services : <title>Object moved to....</title> - bing-maps

I'm trying to use Bing Spatial Data Service of Microsoft by using Java from my server. (I used this code : How to send HTTP request in java?) but it doesnt work at all.
What I want to do: get latitude and longitude from a given adress
public static void main(String[] args) throws IOException {
System.out.println(SendRequete());
}
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
HttpURLConnection connection = null;
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
I keep having the same results:
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
</body></html>ed to here.</h2>
ml><head><title>Object moved</title></head><body>
If I copy and paste on y browser it works fine... Any idea of where the problem is

Looks like you are using the Bing Maps REST services not the Bing Spatial Data Services. The REST services can geocode individual locations on demand, while the Spatial Data Services can geocode up to 200,000 locations in a single request.
Assuming you mean the REST services, yes, the URL you are creating is correct. However you are passing in part of the URL as URL parameters when you shouldn't be. Also, you need to make a GET request, not a POST request. Here is a modified version of your code that should work.
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
URL url = new URL(targetURL + urlParameters);
URLConnection connection = url.openConnection();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Related

Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token during generating access token

I am using the admin sdk API to retrieve all G Suite users. We require an access token for this. AWS is used to host our website. I've tried a few different codes to generate access token, but they always return error
"Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token."
I have no idea why this error is occurring. My code is running smoothly, generating access token and retrieving every user domain wise in a local environment. Any help in why actually I am getting this error. have i missed something? any help in it.
This is my code.
private String getAccessToken()
{
String accessToken="";
try
{
Map<String,Object> params = new LinkedHashMap<>();
params.put("grant_type","refresh_token");
params.put("client_id",client_id);
params.put("client_secret",client_secret);
params.put("refresh_token",refresh_token);
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet())
{
if(postData.length() != 0)
{
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
accessToken = json.getString("access_token");
return accessToken;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return accessToken;
}

Get body of Bad Request httpURLConnection.getInputStream()

I've been working on a portlet that calls Rest API. When the API is called and the requested data doesn't exist, it returns an appropriate error message in JSON format (with Bad request http code - 400), and if the id exists, it returns the requested data in json (with code 200).
How can I get the body of response (that contains error description) because invoking httpConn.getInputStream() method throws exception in case the response is bad request error.
Code:
HttpURLConnection httpConn = null;
URL url = new URL("http://192.168.1.20/personinfo.html?id=30");
URLConnection connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "utf-8");
BufferedReader br = null;
if (!(httpConn.getResponseCode() == 400)) {
br = new BufferedReader(new InputStreamReader((httpConn.getInputStream())));
String output;
StringBuilder builder = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
builder.append(output);
return builder.toString();
}else
here should catch the error message. :)
In case of non-successful response codes, you have to read the body with HttpURLConnection.getErrorStream().
you can get body of Bad Request in HttpURLConnection using this code :
InputStream errorstream = connection.getErrorStream();
String response = "";
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(errorstream));
while ((line = br.readLine()) != null) {
response += line;
}
Log.d("body of Bad Request HttpURLConnection", "Response: " + response);
Use Apache Httpclient:
String url = "http://192.168.1.6:7003/life/lifews/getFirstInstallment.html?rootPolicyNo=1392/2126/2/106/9995/1904&token=1984";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null)
result.append(line);
System.out.println(result);

Paypal Rest services - Response: Internal Service Error

This is my code. I am not using Maven or curl.
String encoding = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
encoding = encoding.replaceAll("\n", "");
URL url1 = new URL("https://api.sandbox.paypal.com/v1/oauth2/token");
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("grant_type", "client_credentials");
conn.setRequestProperty("Authorization", "Basic " + encoding);
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() == 500) {
InputStream error = conn.getErrorStream();
BufferedReader er = new BufferedReader(new InputStreamReader(error));
String erLine;
while ((erLine = er.readLine()) != null) {
System.out.println(erLine);
}
}
InputStream content = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
conn.disconnect();
OUTPUT:
500
{"name":"INTERNAL_SERVICE_ERROR","information_link":"https://api.sandbox.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR","debug_id":"023ff49775e72"}
PROBLEM:
Well, when I do this call using curl, it gives me an appropriate response. Are the services not equipped to do communication is this way ?
Can you print your Authorization header and inspect whether it's correctly populated? We are currently returning a HTTP500 if your Authorization header is empty (which we'll change to return a more appropriate error obviously).

Blackberry HttpConnection and query string

I've been having some trouble connecting to a uri when I append a query string... I always get back 400 http code... however when I try the browser, same url, everything goes smooth...
This is what I have:
String query = "q=hello";
byte[] queryBytes = query.getBytes();
Somewhere in my code I open an HttpConnection using the queryBytes like this:
String uri = "https://www.google.co.ve/search" + "?" + new String(queryBytes);
HttpConnection request = (HttpConnection) Connector.open(uri);
request.getResponseCode();
If I don't use bytes for my connection everyting works fine:
String uri = "https://www.google.co.ve/search?q=hello";
Thanks in advance
When i try this, iam getting http code 200.
try {
String httpURL = "https://www.google.co.ve/search?q=hello";
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.GET);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
httpConn.close();
Dialog.alert(responce);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}