while using HttpURLConnection is it necessary to use disconnect() - httpurlconnection

Can anyone please explain what will be the impact if I dont use disconnect() while using HttpURLConnection. I am sending and recieving data through the connection. and closing the input and output streams. Is that enough or I should explicitely use disconnect().
URL url = new URL(urlname);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("POST");
urlconnection.setDoOutput(true);
urlconnection.setConnectTimeout(s_time);
OutputStreamWriter out = new OutputStreamWriter(urlconnection.getOutputStream());
out.write(postData);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
String somestring;
while ((somestring = in.readLine()) != null) {
data += somestring;
}
in.close();

Related

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

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;
}
}

Hi All, I am struggling in rest API where i need to post an XML in body with header and get the response, can anyone post an example of how to do it?

String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it
You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}

How to handle response Content Type Audio when accessing REST API?

Am using Voice RSS to do text to speech translation for my java application. I have used clients like RESTY in my past to handle simple json requests which am comfortable with. But in this case, the server (Voice RSS) is returning content type as audio, am unsure how to handle and unwrap this as a java client. Any help would be greatly appreciated
Thanks
Karthik
I figured out that you can use Url and BufferedInputStream to download the response from the web service as a byte array or as an OutputStream which you can save it as anything.
InputStream in = null;
ByteArrayOutputStream outputStream = null;
byte[] byteArray = null;
try {
URL link = new URL("YOUR_URL");
in = new BufferedInputStream(link.openStream());
outputStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
outputStream.write(buf, 0, n);
}
byteArray = outputStream.toByteArray();
}catch (Exception ex){
throw ex;
}finally {
if(in != null) in.close();;
if(outputStream != null) outputStream.close();
}

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).