I am new to webservice and I am in the learning phase. Not much of the online content gives information about the use of MovieDB API webservice. Well for not I am just focusing on trying to get a movie information on the screen.
So the as per the API I am requesting the information and I am getting the JSON response when I paste http://api.themoviedb.org/3/movie/550?api_key=MYKEY in the browser.
I want to write a webservice using JAVA,SOAP to parse the JSON and fetch the required information. I tried using HttpURLConnection and then use BufferedReader but its not working.
Kindly suggest me some better options. Any links/blogs will be helpful.
This is the code snippet.
public class TestJSON {
/**
* #param args
*/
public static void main(String[] args) {
try{
URL url = new URL("http://api.themoviedb.org/3/movie/550?api_key=MYKEY/3/movie/550");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
String input = "";
OutputStream os = con.getOutputStream();
os.write(input.getBytes());
os.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
}
catch(MalformedURLException m){
System.out.println("Malformed URL");
}
catch(IOException ioe){
System.out.println("IO exception");
}
}
}
Thanks in advance.
Zingo
Try this code to read the output from the url:
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
Related
I just wrote a simple server with flask and send a http post requset to the server from an Android App. But I failed to read the response in the Android App. The app throw an exception:
My flask code is:
#app.route('/zsj',methods = ['POST'])
def show_data():
data = request.get_json()
print request.values #json.loads(data)#request.get_json()
#data = json
#print data
return "aaaa"#jsonify({'w':'u'})
My android App just use the HttpURLConnection class to send a post and get a respones from the server, which is expected as a string: 'aaaa'. We tried to read out the string but failed.
And my Android code is
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
// Connect to the server
URL url = new URL("http://ec2-35-164-172-186.us-west-2.compute.amazonaws.com:5000/zsj");
JSONObject postDataParams = new JSONObject();
// Display command
postDataParams.put("Weather", "email");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
responseMessage = conn.getResponseMessage();
int responseCode=conn.getResponseCode();
responseCode2=responseCode;
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
// jtest=conn.getInputStream().read(data);
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
StringBuffer sb = new StringBuffer("");
String line="";
StringBuffer sb2 = new StringBuffer("");
// in.readLine();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
// jtest="abc";
// jtest=sb.toString();
while((line = er.readLine()) != null) {
sb2.append(line);
break;
}
in.close();
er.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
My App code just throw an exception at
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
Anyone knows how to solve the problem
I have doubts about send HTTP Post using querystring.
I have the follow code below but thie code not working. I try send by web service the user and password, embedded in URL, but it not working. this code cannot connect on web-service.
#Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user="+user+"&senha="+password);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return result;
}
I think you mean GET request not POST,
and you should encode the variables in the query params, "user" and "password" in your case.
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user=" + URLEncoder.encode(user, "UTF-8")+"&senha="+ URLEncoder.encode(password, "UTF-8"));
I'm accessing RabbitMQ Queue information from java code.
public class NewClass {
private static Object Base64Converter;
public static void main(String args[])
{
try {
String credentials = "test" + ":" + "test";
String encoding = base64Encode(credentials);
URL url = new URL("http://192.168.0.30:15672/api/queues");
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
private static String base64Encode(String stringToEncode)
{
return DatatypeConverter.printBase64Binary(stringToEncode.getBytes());
}
java.io.IOException: Server returned HTTP response code: 401 for URL: http://192.168.0.30:15672/api/queues
You prepare a URLConnection with proper authentication but then you don't use it when you call url.openStream(). This should work:
...
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
uc.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
I have a piece of code to bring data from SharePoint to Unix using HttpURLConnection. The code works fine when I compile it using Java 1.5 on the server. The data is displayed on the console. But the same doesn't work when I try with Java 1.7. The Response code returned is "401". Message is "Unauthorized access".
If it is some authentication issue then why it is not coming up in the java 1.5 compiled class. Is anybody aware of any changes in the HttpURLConnection library specific to this. I only found 1 change added in Java 1.7 for streaming length limit. Any help appreciated !!
Below is snapshot of the code:
public class RestMain {
public static void main(String[] args)
{
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println(getRequestingScheme());
return new PasswordAuthentication ("Userid", "Password".toCharArray());
}
});
try{
System.out.println(RestGet("SharePoint URL"));
}
catch(Exception e)
{
System.out.println("error");
e.printStackTrace();
}
}
public static String RestGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
System.out.println("URL " + url.toString());
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
System.out.println("Response Code" + conn.getResponseCode());
System.out.println("after connect");
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
conn.getResponseMessage();
System.out.println("after Response");
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
System.out.println(sb);
return (sb.toString().substring(1,500));
}
}
I just try to post data to google by using the following code,but always got 405 error,can anybody tell me way?
package com.tom.labs;
import java.net.*;
import java.io.*;
public class JavaHttp {
public static void main(String[] args) throws Exception {
File data = new File("D:\\in.txt");
File result = new File("D:\\out.txt");
FileOutputStream out = new FileOutputStream(result);
OutputStreamWriter writer = new OutputStreamWriter(out);
Reader reader = new InputStreamReader(new FileInputStream(data));
postData(reader,new URL("http://google.com"),writer);//Not working
//postData(reader,new URL("http://google.com/search"),writer);//Not working
sendGetRequest("http://google.com/search", "q=Hello");//Works properly
}
public static String sendGetRequest(String endpoint,
String requestParameters) {
String result = null;
if (endpoint.startsWith("http://")) {
// Send a GET request to the servlet
try {
// Send data
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length() > 0) {
urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(result);
return result;
}
/**
* Reads data from the data reader and posts it to a server via POST
* request. data - The data you want to send endpoint - The server's address
* output - writes the server's response to output
*
* #throws Exception
*/
public static void postData(Reader data, URL endpoint, Writer output)
throws Exception {
HttpURLConnection urlc = null;
try {
urlc = (HttpURLConnection) endpoint.openConnection();
try {
urlc.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new Exception(
"Shouldn't happen: HttpURLConnection doesn't support POST??",
e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
OutputStream out = urlc.getOutputStream();
try {
Writer writer = new OutputStreamWriter(out, "UTF-8");
pipe(data, writer);
writer.close();
} catch (IOException e) {
throw new Exception("IOException while posting data", e);
} finally {
if (out != null)
out.close();
}
InputStream in = urlc.getInputStream();
try {
Reader reader = new InputStreamReader(in);
pipe(reader, output);
reader.close();
} catch (IOException e) {
throw new Exception("IOException while reading response", e);
} finally {
if (in != null)
in.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new Exception("Connection error (is server running at "
+ endpoint + " ?): " + e);
} finally {
if (urlc != null)
urlc.disconnect();
}
}
/**
* Pipes everything from the reader to the writer via a buffer
*/
private static void pipe(Reader reader, Writer writer) throws IOException {
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0) {
writer.write(buf, 0, read);
}
writer.flush();
}
}
405 means "method not allowed". For example, if you try to POST to a URL that doesn't allow POST, then the server will return a 405 status.
What are you trying to do by making a POST request to Google? I suspect that Google's home page only allows GET, HEAD, and maybe OPTIONS.
Here's the body of a POST request to Google, containing Google's explanation.
405. That’s an error.
The request method POST is inappropriate for the URL /. That’s all we know.