I am trying to get a JSON Object from an API while using an API Url. This works perfectly when I test it in Postman, but when I try it in my Spring application, it returns 405 with message(The method is not allowed for the requested URL)
My Java Code:-
URL tokenURL = new URL("https://something.in/v1/token");
HttpURLConnection tokenConnection = (HttpURLConnection) tokenURL.openConnection();
tokenConnection.setRequestMethod("GET");
tokenConnection.setConnectTimeout(Integer.parseInt(env.getProperty
("common.webServiceCall.maxTimeOut")));
tokenConnection.setReadTimeout(Integer.parseInt(env.getProperty
("common.webServiceCall.maxTimeOut")));
tokenConnection.setRequestProperty("Content-Type", "application/json");
tokenConnection.setRequestProperty("Accept", "application/json");
tokenConnection.setRequestProperty("X-IBM-Client-Id", "45878d21-469c-b68e-34b1suds34c");
tokenConnection.setRequestProperty("X-IBM-Client-Secret", "ytGThJH4sW7hY2skhJHG65uC7xH7v645fsdfkjgFGHDFgcvhg");
tokenConnection.setDoInput(true);
tokenConnection.setDoOutput(true);
OutputStream tokenStream = null;
try {
tokenStream = tokenConnection.getOutputStream();
} catch (RemoteException e) {
e.printStackTrace();
}
try {
for(int i = 0; i < 3; i++) {
tokenConnection.connect();
if (tokenConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (tokenConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((tokenConnection.getInputStream())));
StringBuilder serviceResponse = new StringBuilder();
String serviceResponseLine;
while ((serviceResponseLine = bufferedReader.readLine()) != null) {
serviceResponse.append(serviceResponseLine);
}
tokenStream.close();
tokenConnection.disconnect();
System.out.println(serviceResponse);
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((tokenConnection.getErrorStream())));
StringBuilder serviceResponse = new StringBuilder();
String serviceResponseLine;
while ((serviceResponseLine = bufferedReader.readLine()) != null) {
serviceResponse.append(serviceResponseLine);
}
tokenStream.close();
tokenConnection.disconnect();
System.out.println(serviceResponse);
}
I have one suggestion, postman can generate source code of request for different programming languages e.g. java and JavaScript and command line tool like cURL.
I suggest use cURL gives you more verbose details that can help you in connection configuration.
Related
I'm working on a HTTP-Client to sent GET-Requests to an API, which responds with proper JSON-Objects even when the HTTP-Status Codes contains an Error such as 401.
public String get(String url){
URL target;
HttpURLConnection connection;
int code = 200;
BufferedReader reader;
String inputLine;
String result = null;
try {
target = new URL(url);
} catch (MalformedURLException ex) {
return result;
}
try {
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//code = connection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
result = "";
while ((inputLine = reader.readLine()) != null){
result += inputLine;
}
reader.close();
} catch (IOException ex) {
return "...";
}
return result;
}
When that's the case, the IOException is thrown and the response isn't written. However, I want to receive the response regardless of the HTTP-Status-Code and hande error handling myself. How can I achieve this?
I don't believe you can do that, but there's https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream-- for getting the payload in case of an error.
I want wrote an API in php for using it in my android app. In the php side I do this for return info in an array
echo json_encode($array)
result of this code is like this, see online result in this link:
{"value":[{"id":"1","name":"kufta","meal":"1","photo_id":"","explanation":"xoshmazas","foodtime":"0000-00-0000:00:00"},{"id":"2","name":"\r\nAsh","meal":"2","photo_id":"","explanation":"sdfdsfsdfdsfdsfsdf","foodtime":"2017-06-26 14:00:00"},{"id":"3","name":"kabab","meal":"3","photo_id":"","explanation":"kabab kheili khoshmaze ast","foodtime":"2017-06-29 00:00:00"}]}
but in java side when I load this, app crash but when I use this json string in this site. Android app works fine
my java code for reading the url content
public class WebService {
private String connectToServer(String address, String requestMethod) {
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(requestMethod);
return inputStreamToString(httpURLConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String inputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = reader.readLine()) != null) {
stringBuilder.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
line 23 : public List<FoodModel> getFoods(){ <-----------Error is here
String response = connectToServer("http://mtg1376.gigfa.com/api/food?day=All","GET");
if(response != null){
List<FoodModel> foodList = new ArrayList<đŸ˜ );
try{
JSONObject mainObject = new JSONObject(response);
JSONArray foodArray = mainObject.getJSONArray("value");
for(int i = 0 ; i< foodArray.length();i++){
JSONObject foodObject = foodArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.id = foodObject.getString("id");
foodModel.name = foodObject.getString("name");
foodModel.meal = foodObject.getString("meal");
foodModel.photo_id = foodObject.getString("photo_id");
foodModel.explanation = foodObject.getString("explanation");
foodModel.foodtime=foodObject.getString("foodtime");
foodList.add(foodModel);
}
return foodList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null; }
}
java error log : https://ibb.co/hQneXk
whats the problem?
I'm working to make a thread that monitors a web api to get the latest announcement via JSON. I cannot test this currently, so I'm unsure if anything needs to be changed with this. I've read through other questions but everyone else doesn't seem to be using a loop to keep getting a response.
public void run(){
try {
URL url = new URL(announcementsURL);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Connection", "keep-alive");
http.setUseCaches(false);
http.setAllowUserInteraction(false);
http.setConnectTimeout(10);
http.setReadTimeout(10);
while (true){
http.connect();
int status = http.getResponseCode();
if (status == 201){
BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(json);
if (!(lastAnnouncement == (long) jsonResponse.get("time"))){
//String announcement = (String) jsonResponse.get("message");
//TODO What to do with announcement...
}
}
http.getInputStream().close();
http.disconnect();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
this.interrupt();
try {
this.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
Previously, i can access the string from php remotely. I find it difficult at first but AsyncTask did the work for me. Now, i can access the result of the query from php to sql server. But I would like to pass a string from my java class to php and as I googled some information, i saw some JSON post and get codes but i can't clearly understand them. Here's my code:
protected String doInBackground(Void... params) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
The string is contained in "sb.toString()". Now how would I add a JSON something in my code to send string from java to php, and also get the result string from php to java as well. Thanks in advance for any help.
If you receive response as JSON format from server, make the json string to JSONObject first. And then read the json data for your use.
try {
JSONObject obj = new JSONObject(sb.toString()); // make string to json obj
Iterator iter = obj.keys(); // get all keys from json obj and iterating
while(iter.hasNext()){
String key = (String)iter.next();
String str = obj.get(key).toString();
// write your code
}
} catch(Exception e) {
e.printStackTrace();
}
Your code already contains the answer of your question. After make url connection, just add parameter for sending your data to server with OutputStreamWriter as like you did for receive the response with InpustStreamReader.
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
// wrtie params
OutputStreamWriter we = new OutputStreamWriter(urlConnection.getOutPutStream());
wr.write(data); // data (make json obj to 'key=value' string)
wr.flush();
wr.close();
// read response
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}enter code here
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.